Reputation: 1615
I'm trying to loop through an array and it keeps saying length
is 0
Screenshot of array:
I've tried for(key in results)...
and for( var i = 0; i < length...
But both don't run anything inside the loop: console.log(results[i]); // Or key if it's a key in loop
I'm sure it's a rookie mistake, can anyone spot it?
The code I'm using:
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;
});
});
When I console.log(records)
as seen above the result is the screenshot. When I loop over it nothing happens because records.length === 0
Edit:
store.where('record.age < 20', function(records){
console.log(records); // Array with property length 3
console.log(records.length); // 0
});
The first console.log
shows the array with records.length === 3
but the second console.log
shows 0
. How?
Upvotes: 0
Views: 979
Reputation: 1522
To iterate an array and produce side effects, use 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));
If on the other hand you need to filter or transform the array, consider using filter, map or reduce instead. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
Upvotes: 0
Reputation: 1883
Without providing code, it's difficult to say if you've made a rookie mistake! I see that you're using length rather than arrayName.length? I don't know the name of your array...
for (var i = 0; i < array.length;i++){
//logic here
};
Upvotes: 1