[英]can't push to array Objects
I have problem with array Objects. 我对数组对象有问题。 I have variable "setting".
我有变量“设置”。 If I write:
如果我写:
var settings=[];
var tempSettings=[{
id:1,
name:"Test1"
},
{
id:2,
name:"Test2"
}
];
settings=tempSettings;
console.log(settings[0]);
All right-all work. 好吧,所有工作。 settings[0]- no problem;
设置[0]-没问题;
But if I received data from file and do: 但是,如果我从文件接收数据并执行以下操作:
jQuery.getJSON("myurl", function(data) {
console.log(data);
var zones=data.split("~");
jQuery.each(zones, function(key, value) {
var set = value.split(",");
var tset={
id:set[0],
name:set[1]
};
settings.push(tset);
});
});
console.log(settings[0]);
This not work settings[0] - undefined. 此设置无效[0]-未定义。 What my mistake?
我有什么错
Data I received and console.log(data); 我收到的数据和console.log(data); get me string data.
给我字符串数据。
Added: 添加:
console.log(tempSettings) in variant hardcodded does: hardcodded的console.log(tempSettings)具有以下功能:
[Object { Id=1, name="Test1"},Object { Id=2, name="Test2"} ] [对象{ID = 1,名称=“ Test1”},对象{ID = 2,名称=“ Test2”}]
and console.log(settings) in received variables does: []. 和console.log(settings)在接收到的变量中:
but in after click in console I see: 但在单击控制台后,我看到:
[0] Object { id="3", name="Test3"}, [1] Object { id="4", name="Test4"}. [0]对象{id =“ 3”,name =“ Test3”},[1]对象{id =“ 4”,name =“ Test4”}。
getJSON
is asynchronous. getJSON
是异步的。 You need to include the console.log
within the callback function: 您需要在回调函数中包含
console.log
:
jQuery.getJSON("myurl", function(data) {
console.log(data);
var zones=data.split("~");
jQuery.each(zones, function(key, value) {
var set = value.split(",");
var tset = {
id:set[0],
name:set[1]
};
settings.push(tset);
});
console.log(settings[0]);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.