如何在javascript中向数组添加新对象(键值对)?

时间:2022-06-09 07:37:55

I have an array as :

我有一个数组:

items=[{'id':1},{'id':2},{'id':3},{'id':4}];

How should I add a new pair {'id':5} to the array?

我该如何向数组中添加一对新的{'id':5}?

3 个解决方案

#1


39  

Use .push:

使用.push:

items.push({'id':5});

#2


2  

Sometimes .concat() is better than .push() since .concat() returns the new array whereas .push() returns the length of the array.

有时.concat()优于.push(),因为.concat()返回新数组,而.push()返回数组的长度。

Therefore, if you are setting a variable equal to the result, use .concat().

因此,如果要将变量设置为等于结果,请使用.concat()。

items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
newArray = items.push({'id':5})

In this case, newArray will return 5 (the length of the array).

在这种情况下,newArray将返回5(数组的长度)。

newArray = items.concat({'id': 5})

However, here newArray will return [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}].

但是,newArray会返回[{'id':1},{'id':2},{'id':3},{'id':4},{'id':5}]。

#3


1  

.push() will add elements to the end of an array.

.push()会将元素添加到数组的末尾。

Use .unshift() if need to add some element to the beginning of array i.e:

如果需要在数组的开头添加一些元素,请使用.unshift(),即:

items.unshift({'id':5});

Demo:

演示:

items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
items.unshift({'id': 0});
console.log(items);

And use .splice() in case you want to add object at a particular index i.e:

如果要在特定索引处添加对象,请使用.splice(),即:

items.splice(2, 0, {'id':5});
           // ^ Given object will be placed at index 2...

Demo:

演示:

items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
items.splice(2, 0, {'id': 2.5});
console.log(items);

#1


39  

Use .push:

使用.push:

items.push({'id':5});

#2


2  

Sometimes .concat() is better than .push() since .concat() returns the new array whereas .push() returns the length of the array.

有时.concat()优于.push(),因为.concat()返回新数组,而.push()返回数组的长度。

Therefore, if you are setting a variable equal to the result, use .concat().

因此,如果要将变量设置为等于结果,请使用.concat()。

items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
newArray = items.push({'id':5})

In this case, newArray will return 5 (the length of the array).

在这种情况下,newArray将返回5(数组的长度)。

newArray = items.concat({'id': 5})

However, here newArray will return [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}].

但是,newArray会返回[{'id':1},{'id':2},{'id':3},{'id':4},{'id':5}]。

#3


1  

.push() will add elements to the end of an array.

.push()会将元素添加到数组的末尾。

Use .unshift() if need to add some element to the beginning of array i.e:

如果需要在数组的开头添加一些元素,请使用.unshift(),即:

items.unshift({'id':5});

Demo:

演示:

items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
items.unshift({'id': 0});
console.log(items);

And use .splice() in case you want to add object at a particular index i.e:

如果要在特定索引处添加对象,请使用.splice(),即:

items.splice(2, 0, {'id':5});
           // ^ Given object will be placed at index 2...

Demo:

演示:

items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
items.splice(2, 0, {'id': 2.5});
console.log(items);