简体   繁体   中英

Javascript forEach array method not changing object properties

Sorry, this may be obvious to some but can someone please explain to me why this function called by a click event does not take the current element in the array that is an object with a property of state:'active', change it to null, and then gets the next element in the array ,that is also an object, and change its state property to 'active', but instead throw an error message like 'Cannot set property 'state' of undefined'?

Thankyou in advance!

var array = [{
    state : 'active'
}, {
    state : null
}, {
    state : null
}];

document.addEventListener('click', function() {
    array.forEach(function(element, index, array) {
        if(element.state === 'active') {
            element.state = null;
            array[index+1].state = 'active';
        }
    });
});

The problem is not that it doesn't do it, it does do it, but then the loop continues and now the next element is "active". It does this until the last element throws and error because you are trying to access an index which is out of the array.

Try this:

var i = null;
array.forEach(function(element, index, array) {
    if(element.state === 'active') {
        i = index;
    }
});

if (i !== null && i + 1 < array.length) { 
    array[i].state = null;
    array[i+1].state = 'active';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM