[英]how can I make an for-loop work with a variable inside a variable
首先,嘿!我在這里已經問過兩次了,都得到了很好的解答。
所以...我想在控制台上進行for循環打印,將所有變量記錄在commands
變量上。
我只想打印BOH
, HALO
和BOOM 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.