[英]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. 所以...我想在控制台上进行for循环打印,将所有变量记录在
commands
变量上。
I would like to print only BOH
, HALO
and BOOM HSAKALAKA
variables, not their texts: BOH!
我只想打印
BOH
, HALO
和BOOM HSAKALAKA
变量,而不打印它们的文本: BOH!
, HALO!
,
HALO!
, BOOM SHAKALAKA!
,
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. commands
不是数组,而是对象。 So, in order to loop through an object we should use its key
property. 因此,为了遍历一个对象,我们应该使用它的
key
属性。
In our case key
is 'BOH)'
and the value of that key
is commands[key]
=> BOH!
在我们的例子中,
key
是'BOH)'
,该key
的值是commands[key]
=> BOH!
. 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.