使用splice将对象添加到对象数组

use*_*527 9 javascript

我有一个对象数组,如下所示:

event_id=[{"0":"e1"},{"0","e2"},{"0","e4"}];
Run Code Online (Sandbox Code Playgroud)

如何向该数组添加元素?

我想到了

event_id.splice(1,0,{"0":"e5"});
Run Code Online (Sandbox Code Playgroud)

谢谢.

mae*_*ics 10

如果你只想在数组的末尾添加一个值,那么push(newObj)函数是最简单的,虽然splice(...)也可以工作(只是有点棘手).

var event_id = [{"0":"e1"}, {"0":"e2"}, {"0":"e4"}];
event_id.push({"0":"e5"});
//event_id.splice(event_id.length, 0, {"0":"e5"}); // Same as above.
//event_id[event_id.length] = {"0":"e5"}; // Also the same.
event_id; // => [{"0":"e1"}, {"0":"e2"}, {"0":"e4"}, {"0":"e5"}]; 
Run Code Online (Sandbox Code Playgroud)

有关该对象的优秀MDN文档,Array请参阅有关阵列上可用的方法和属性的参考.

[编辑]要在数组的中间插入一些东西,你肯定想要使用splice(index, numToDelete, el1, el2, ..., eln)处理在任何位置删除和插入任意元素的方法:

var a  = ['a', 'b', 'e'];
a.splice( 2,   // At index 2 (where the 'e' is),
          0,   // delete zero elements,
         'c',  // and insert the element 'c',
         'd'); // and the element 'd'.
a; // => ['a', 'b', 'c', 'd', 'e']
Run Code Online (Sandbox Code Playgroud)


use*_*527 7

因为我想在数组的中间添加对象,所以我结束了这个解决方案:

var add_object = {"0": "e5"};
event_id.splice(n, 0, add_object); // n is declared and is the index where to add the object
Run Code Online (Sandbox Code Playgroud)