Question

I have an object with string values attached to the same property that I wish to remove using a function if that value is present. To achieve this I have placed the string values into an array, iterated through them and want to remove the value using splice() . The problem is that splice() doesn't seem to recognize the array counter. It always removes the first item in the array even when the counter is is higher. I've checked the code and the loop is working correctly.

I've not seen anything online to suggest that splice can't be used with a variable at the index. How can I make splice use the counter to remove the relative value ?

var obj = {

className: 'open menu next thing'
}

function removeClass(elem, cls) {

var arr = elem.className.split(' ');

for(var i = 0; i < arr.length; i++) {
    if(arr[i] == cls) {
        alert(arr[i]);
        var splCout = arr.splice(arr[i], 1);
        alert(splCout);
    }
}
var str = arr.join(' ');
alert(str);
}

removeClass(obj, 'next');
Was it helpful?

Solution

You have 2 different problem to fix:

1- you are modifying the array object in your for loop, after the first splice the array is changed and the arr.length is totally different for the rest of your loop items, to prevent it create a variable like len and set it to the length of your array once.

but if you change the loop the other way round, you would need it once:

for(var i = arr.length; i >= 0; i--) {
    if(arr[i] == cls) {
        alert(arr[i - 1]);
        var splCout = arr.splice(arr[i - 1], 1);
        alert(splCout);
    }
}

2- the next and the more important problem is the indexes of the array, when you remove an index the other indexes change (i......n) and the code won't work properly, but as you see when you iterate the array this way even when you remove the index, the other indexes back to the zero (i....0) don't change.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top