简体   繁体   English

如何通过对象循环以返回对象而不是字符串?

[英]How to get a loop through objects to return an object instead of string?

I have an object, cards, which is made up of other objects. 我有一个对象,卡片,由其他对象组成。

When I loop through cards, I expect other objects to get returned. 当我遍历卡片时,我希望其他对象能够返回。 Instead, only a string is returned. 而是只返回一个字符串。 I've included what gets returned inline in the code below. 我已经在下面的代码中内联了返回的内容。

console.log(typeof cards); //returns object
console.log(cards); //returns the 3 objects: [Object, Object, Object]
console.log(cards.length); //returns 3

for (var card in cards){
    console.log(typeof card); //returns 0,1,2 as a string, but it should return another object
};

for...in loops iterate properties of an object, not values. for...in循环迭代对象的属性,而不是值。

For example: 例如:

var cards = ['a', 'b', 'c'];
for(var prop in cards) {
    console.log(prop);        //  0,   1,   2
    console.log(cards[prop]); // 'a', 'b', 'c'
}

Moreover, note that for...in loops are a bad way of iterating arrays . 此外,请注意for...in循环是迭代array的一种不好方法

ECMAScript 6 introduces for...of loops, which iterate values: ECMAScript 6引入了for...of循环,该循环迭代值:

var cards = ['a', 'b', 'c'];
for(var val of cards) {
    console.log(val);         //  'a', 'b', 'c'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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