Mootools : I want to traverse following array in mootools
I am learning mootools. I have an array in following format. I want to traverse it in for loop but dont know how to do it.
{'apple' : { 'prize' : 10 , 'color' : 'Red' } ,
'banana' : { 'color' : 'red', 'prize' : 20, 'quantity' : 12 } }
I am getting above structure of array from another module thats why i c开发者_如何学运维ant change its structure.
MooTools has a function for this as well, so you don't need to use the hasOwnProperty
check yourself:
Object.each({ 'prize' : 10 , 'color' : 'Red' }, function(value, key){
// what you like to do.
});
See the documentation: http://mootools.net/docs/core/Types/Object#Object:Object-each
It is indeed important to know the difference between an array and object. The above example uses an Object literal.
For arrays you could use Array:each.
[1, 2, 3, 4].each(function(value, key){
// what you like to do.
});
Docs: http://mootools.net/docs/core/Types/Array#Array:each
But as mentioned in the other answer, you could do this with for (var key in obj){}
loops for objects, and for (var i = 0, l = arr.length; i < l; i++){}
loops for arrays in plain JavaScript
Those are objects, not arrays.
Example: http://jsfiddle.net/AkVvY/
var obj = {'apple' : { 'prize' : 10 , 'color' : 'Red' } ,
'banana' : { 'color' : 'red', 'prize' : 20, 'quantity' : 12 } };
for( var name in obj ) {
alert( name + ': ' + obj[name].color );
}
You don't need a library for this.
If you're concerned that there may be additions to Object.prototype
, then do this:
Example: http://jsfiddle.net/AkVvY/1/
for( var name in obj ) {
if( obj.hasOwnProperty( name ) ) {
alert( name + ': ' + obj[name].color );
}
}
精彩评论