我是javascript的新手,开始学习对象和数组,我只想知道为什么我的数组看起来像是空的,但是当您单击它时就具有值了?参见下面的代码,我正在使用nedb
和Framework7
。
var DeviceArray = new Array();
db.find({}, function (err, docs) {
docs.forEach(function(element) {
$$("#listDevice").append('<li><a href="single/'+element._id+'">'+element.device+'</a></li>');
DeviceArray.push(element);
});
});
现在将DeviceArray放入对象中。
user: [{
firstName: 'Jhon',
lastName: 'Doe',
}],
products: [
{
id: '1',
title: 'Apple iPhone 8'
},
{
id: '2',
title: 'Apple iPhone 8 Plus'
},
{
id: '3',
title: 'Apple iPhone X'
},
],
devices: DeviceArray
然后,当我尝试检查对象时,就会出现。
设备看上去是空的,但是当您单击它时会出现。
我以为可以,但是当我尝试对设备Array进行迭代时,它什么也不返回,所以我的问题是如何解决这个问题?我已经检查了
docs
输出,请参见下图,任何建议都很好。最佳答案
我已经在jsfiddle中重新创建了您的方案。
https://jsfiddle.net/1j4gu2f1/
有两个控制台,带有和不带有setTimeout的两个控制台都将在折叠状态下给出不同的表示形式,而在展开状态下给出相同的结果。
我认为代码是不言自明的。
var devices = [];
setTimeout(function(){ //data loaded after 1000 ms
devices.push({"name":"hello"});
devices.push({"name":"world"})
},1000);
console.log(devices); // will show empty devices
setTimeout(function(){
console.log(devices); // will show devices array
},1000)