example:
var array = [1, 2, 3, 4];
for (var i = 0; i < array.length; i ++) {
console.log(i);
}
// this console.logs the placement/key/prop of i in the array 0, 1, 2, 3 not the value of 1, 2, 3, 4;
for (var i = 0; i < array.length; i ++) {
console.log(array[i]);
}
//this console.logs the value of each key so this array console.logs 1, 2, 3, 4;
the special for in loop is only for arrays;
var obj = { name: 'josh', age: '34', haircolor: 'black', address: {street: '1012 old mountain rd', city: 'Denver', country: 'USA'} } for (var prop in obj) { console.log(prop) }
//this console.logs the keys of the object asking for the name of the key
name
age
haircolor
address
for (var prop in obj) { console.log(obj[prop]) }
//this console.logs the values of the object asking for the object's property.
josh
34
black
Object {street: "1012 old mountain rd", city: "Denver", country: "USA"}
for (var prop in obj) {
console.log(obj[prop].city)
// this iterates through the object values then looks for the value of a key named city
}
for (var prop in obj) {
console.log(obj[prop].city)
// this iterates through the object values then looks for the value of a key named city
}
No comments:
Post a Comment