简体   繁体   中英

Unexpected elements being spliced out of an array?

I have some javascript ( here's the JSFiddle)

var array = new Array();
array.push('a');
array.push('b');
var index = array.indexOf('b');
array = array.splice(index, 1); // splice out the element
alert(array[0]); // Which one is left?

I would expect that the alert box will return 'a' because 'b' is being removed, however the dialog is showing 'b'.

Similarly if I try to remove 'a'

var array = new Array();
array.push('a');
array.push('b');
var index = array.indexOf('a');
array = array.splice(index, 1); // splice out the element
alert(array[0]);

Then 'a' is returned.

Why are (what I believe to be) incorrect values being spliced out of the array?

I'm using chrome if that helps.

From the MDN docs on Array.prototype.splice() :

Returns

An array containing the removed elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

splice() is not a "remove" function. The splice() method changes the content of an array, adding new elements while removing old elements.
This means that the actual array itself is changed.

To remove an item from an array, you should use Array.prototype.filter() :

 var array = ['a', 'b', 'stringToRemove', 'c']; var filtered = array.filter(function(element){ return element !== 'stringToRemove'; }); alert(JSON.stringify(filtered)) 

Instead of

array = array.splice(index, 1); // splice out the element

do this,

array.splice(index,1);

Because the method returns an array of spliced out items which is replacing your modified array.

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