Javascript循环遍历对象数组

时间:2016-08-09 10:13:05

标签: javascript arrays object

我试图循环播放一个数组并且一直说using namespace std; string x; int main() { cout << "Welcome to the citation machine. What do you want to cite?" << endl; cin >> x; if (x == "book") { cout << "What is the name of the book?"; } } length

数组截图:

screenshot

我已尝试0for(key in results)... 但两者都不会在循环中运行任何内容:for( var i = 0; i < length...

我确定这是一个新手的错误,有人能发现它吗?

我使用的代码:

console.log(results[i]); // Or key if it's a key in loop

如上所示,当我 var store = new Lawnchair({name: 'testing'}, function (store) { // Create an object var me = {key: 'Jordy', age: 19, date_of_birth: "1233-09-06"}; var mee = {key: 'dude', age: 17, date_of_birth: "2222-09-06"}; var meee = {key: 'gast', age: 8, date_of_birth: "5555-09-06"}; // Save it store.save(me); store.save(mee); store.save(meee); // Access it later... Yes even after a page refresh! store.where('record.age < 20', function (records) { var html = ""; var list = document.getElementById('people'); // for (var i = 0; i < records.length; i++) { // var record = records[i]; // html += "<li>" + record.key + " is " + record.age + " years old and was born on " + record.date_of_birth + "</li>"; // } for(var key in records){ console.log("SD"); } console.log(records); list.innerHTML = html; }); }); 时,结果就是截图。当我循环时,没有任何事情发生,因为console.log(records)

修改

records.length === 0

第一个store.where('record.age < 20', function(records){ console.log(records); // Array with property length 3 console.log(records.length); // 0 }); 显示数组console.log,但第二个records.length === 3显示console.log。怎么样?

2 个答案:

答案 0 :(得分:1)

如果没有提供代码,很难说你是否犯了一个菜鸟错误!我看到你使用的是length而不是arrayName.length?我不知道你的阵列的名字......

for (var i = 0; i < array.length;i++){
    //logic here
    };

答案 1 :(得分:0)

要迭代数组并产生副作用,请使用https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

E.g

[1,2,3,4].forEach(num => console.log(num));

另一方面,如果您需要过滤或转换数组,请考虑使用filter,map或reduce。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array