我正在尝试做一些非常简单的事情,但我认为我犯了一个愚蠢的错误。
我有一个充满对象的数组,我有一个新对象要放入该数组中。我的代码如下所示:
var data = [ { id: 'S1', url: '1.html' } ];
var newData = { id: '3', url: '3.html' };
console.log(data.push(newData))
出于某种原因,这会一直打印“2”。
Here是一个 fiddle
谁能告诉我我犯了什么愚蠢的错误?
最佳答案
您正在正确使用 .push()
。但是,显然期待 a different return
value :
Returns
The new
length
property of the object upon which the method was called.
如果您尝试记录 Array
本身,您需要单独执行此操作:
data.push(newData);
console.log(data);
至于 fiddle ,你可以使用JSON.stringify()
序列化对象。
data.push(newData);
$('#here').text(JSON.stringify(data, null, 2))
[ { "id": "S1", "url": "1.html" }, { "id": "3", "url": "3.html" } ]
简单地使用 .text(data)
将使用每个 Object
's toString()
,这只会导致:
[object Object],[object Object]
关于javascript - .push() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18346487/