對象的數組我有對象的數組,看起來像這樣:添加對象與拼接
event_id=[{"0":"e1"},{"0","e2"},{"0","e4"}];
怎樣的元素添加到陣列?
我想
event_id.splice(1,0,{"0":"e5"});
致謝。
對象的數組我有對象的數組,看起來像這樣:添加對象與拼接
event_id=[{"0":"e1"},{"0","e2"},{"0","e4"}];
怎樣的元素添加到陣列?
我想
event_id.splice(1,0,{"0":"e5"});
致謝。
因爲我要添加的對象數組的中間,我這個解決方案結束:
var add_object = {"0": "e5"};
event_id.splice(n, 0, add_object); // n is declared and is the index where to add the object
怎麼樣刪除對象,其中value =「E5」? – 2013-05-17 09:31:49
event_id.push({"something", "else"});
嘗試使用.push(...)
^
如果你只是想添加一個值到一個數組的結尾,則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"}];
用於陣列上可用的方法和屬性的良好參考見優良MDN documentation for the Array
object。
[編輯]要插入一些到陣列的中間那麼你肯定會想使用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']
我想添加對象的數組的中間。 – user823527 2012-03-30 16:35:00
@ user823527:看到我更新的答案。 – maerics 2012-03-30 16:56:23
那麼你可以通常使用:
event_id[event_id.length] = {"0":"e5"};
或(在稍慢)
event_id.push({"0":"e5"});
但如果你的意思是一個元素插入到一個數組的中間,而不是總是在最後,那麼我們將不得不拿出一些更創造性。
希望它能幫助,
ISE
這一點已經在這裏找到答案: http://stackoverflow.com/a/12189963/984780 – 2012-08-31 14:46:41