Reputation: 55293
I have the following array of arrays:
[ 'markdown',
[ 'para', '"one"' ],
[ 'hr' ],
[ 'para', '"two"' ],
[ 'para', '"three"' ] ]
I made a loop to only match those arrays with double quotes:
for (i = 1; i < jsonml.length; i++) {
if (typeof jsonml[i][1] === "string" && jsonml[i][1].match(/"/g)) {
var p = jsonml[i]
console.log(p)
}
// more code
if (jsonml[i][0] === 'hr') {
var hr = jsonml[i]
var p = jsonml[i + 1]
hr.splice(0, 1, 'para', '* * *')
p.splice(1, 0, {'class': 'noind'})
}
For some reason console.log(p)
only outputs:
[ 'para', '"one"' ]
[ 'para', '"three"' ]
Is [ 'hr' ]
somehow making [ 'para', '"two"' ]
not to match the if statement? If so how to fix it so that [ 'para', '"two"' ]
is matched, too?
if (jsonml[i][0] === 'hr') {
var hr = jsonml[i]
var p = jsonml[i + 1]
hr.splice(0, 1, 'para', '* * *')
p.splice(1, 0, {'class': 'noind'})
}
EDIT:
I think the problem is with the if statement below, since console.log(jsonml[i][1])
outputs:
"one"
undefined
{ class: 'noind' }
"three"
I thought the if statements would execute in order?
Upvotes: 0
Views: 47
Reputation: 48425
The problem appears to be because you are modifying the array while you are still iterating over it. Which means that the [ 'para', '"two"' ]
item is no longer there by the time you get round to it.
Usually, you should always avoid modifying a collection while you are looping over it. If you need to make changes then do them either before or afterwards (which can also be using a separate loop if you need to)
Upvotes: 4