简体   繁体   中英

how can I make an for-loop work with a variable inside a variable

first of all, HEY!, I've already asked twice here and both got good answuers that helped a lot.

So... I want to my for-loop print on the console log all my variables on commands variable.

I would like to print only BOH , HALO and BOOM HSAKALAKA variables, not their texts: BOH! , HALO! , BOOM SHAKALAKA! .

var commands = {
'BOH': {text: 'BOH!'},
'HALO': {text: 'HALO!'},
'BOOM SHAKALAKA': {text: 'BOOM SHAKALAKA!'},
};

for (number = 0; number < commands.lenght; number++){
    console.log(commands[number]);
};

Something like this DEMO ?

var commands = {
'BOH)': {text: 'BOH!'},
'HALO': {text: 'HALO!'},
'BOOM SHAKALAKA': {text: 'BOOM SHAKALAKA!'},
};

for(key in commands){

if(commands.hasOwnProperty(key)){ //get only the properties of the current object and skip inherited properties 

    console.log("variable - " + key + " " + "value - " + commands[key].text);

}

};

In your example, you are looping through an array that doesn't exist. commands is not an array, it's an object. So, in order to loop through an object we should use its key property.

In our case key is 'BOH)' and the value of that key is commands[key] => BOH! .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM