首先,嘿!我已经在这里问过两次了,而且都得到了很好的答案,这对我有很大帮助。
所以..。我想要在控制台日志上打印我的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]);
};发布于 2014-05-31 14:04:27
像这样的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);
}
};在您的示例中,您正在循环遍历一个不存在的数组。commands不是数组,而是对象。因此,为了循环一个对象,我们应该使用它的key属性。
在我们的例子中,key是'BOH)',而key的值是commands[key] => BOH!。
https://stackoverflow.com/questions/23970873
复制相似问题