簡體   English   中英

如何使用變量內的變量進行for循環工作

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

首先,嘿!我在這里已經問過兩次了,都得到了很好的解答。

所以...我想在控制台上進行for循環打印,將所有變量記錄在commands變量上。

我只想打印BOHHALOBOOM HSAKALAKA變量,而不打印它們的文本: 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]);
};

像這樣的演示

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);

}

};

在您的示例中,您正在遍歷一個不存在的數組。 commands不是數組,而是對象。 因此,為了遍歷一個對象,我們應該使用它的key屬性。

在我們的例子中, key'BOH)' ,該key的值是commands[key] => BOH!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM