简体   繁体   中英

Javascript remove item on array using splice() not working

So I have an array like this var arr = [foo1:"bar1", foo2:"bar", foo3:"bar3"] .

Then I used this arr.splice(index, 1); given that the index is dynamic lets just say it's 0 but the value foo1:"bar1" wasn't removed from the array .

Also the above array works on my code but it shows an error on JSFiddle. I have no idea why.

Thanks.

EDIT I dont know why it doesn't show an error on my console but here's how I did it.

var arr = [];

I dynamically added value to the array by doing

arr["foo"] = "bar";

which resulted to [foo:"bar"];

Any idea guys?

EDIT 2

Here's the screenshot of the console. 在此处输入图片说明

Structure of this array is not valid.

var arr = [foo1:"bar1", foo2:"bar", foo3:"bar3"];

An array will have comma-separated items within square braces [] , not key values

If you want to have key values, then it should be Object with curly braces {}

var arr = {foo1:"bar1", foo2:"bar", foo3:"bar3"};

and if you want to remove first property from the arr , then do

var keys = Object.keys( arr );
delete arr[ keys[ 0 ] ];

For adding a key value,

arr[ "foo5" ] = "bar";

Long way:

var arr = [];

var foo1 = {};
foo1['foo1'] = 'bar1';

var foo2 = {};
foo1['foo2'] = 'bar2';

arr.push(foo1);
arr.push(foo2);

alert(arr.length); // output: 2

var index = arr.indexOf(arr, foo1); // or var index = $.inArray(arr, foo1);
arr.splice(index, 1);

alert(arr.length) // output: 1

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