如何使用console.log语句访问james的属性并获取以下输出
的console.log(iterator.next()值。); “詹姆斯的
的console.log(iterator.next()值); 5'10
的console.log(iterator.next()值); 185
const james = {
name: 'James',
height: `5'10"`,
weight: 185};
const key=Object.keys(james);
const iterator = james[[Symbol.iterator]]();
将james
对象转换为可迭代对象。
james
对象的密钥
james
对象我是JavaScript和编程的新手。
提前致谢
答案 0 :(得分:1)
将以下迭代器方法添加到对象:
const james = {
name: 'James',
height: `5'10"`,
weight: 185,
[Symbol.iterator]() {
let nextIndex = 0;
const entries = Object.entries(this);
return {
next: () => {
if(nextIndex >= entries.length) {
return {done: true};
}
const [key, value] = entries[nextIndex++];
return {value: { key, value }, done: false};
}
};
}
};
const iterator = james[Symbol.iterator]();
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log('----------------');
// or iterate with for...of
for(const vk of james) {
console.log(vk);
}
或者作为@Bergi suggested,而不是手动创建迭代器方法,您可以将条目映射到对象数组,并返回数组的迭代器:
const james = {
name: 'James',
height: `5'10"`,
weight: 185,
[Symbol.iterator]() {
return Object.entries(this).map(([key, value]) => ({key, value}))[Symbol.iterator]();
}
};
const iterator = james[Symbol.iterator]();
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log('----------------');
// or iterate with for...of
for(const vk of james) {
console.log(vk);
}
答案 1 :(得分:0)
只需在代码中使用ES8 Object.values
代替Object.keys
即可获取值:
const iterator = Object.values({
name: 'James',
height: `5'10"`,
weight: 185
})[Symbol.iterator]();
console.log(iterator.next().value); // James
console.log(iterator.next().value); // 5'10"
console.log(iterator.next().value); // 185
答案 2 :(得分:0)
你已经在这里得到了一些很好的建议,但是如果你能使用发电机,我想我还会再添加一个很好的建议:
const james = {
name: 'James',
height: `5'10"`,
weight: 185,
*[Symbol.iterator]() {
for (const [key, value] of Object.entries(this)) {
yield { key, value };
}
},
};
当然是
const james = {
name: 'James',
height: `5'10"`,
weight: 185,
};
const key = Object.keys(james);
const iterator = james[[Symbol.iterator]]();
console.log(iterator.next().value); // 'James'
console.log(iterator.next().value); // 5'10
console.log(iterator.next().value); // 185
您也可以避免自定义迭代器并执行
const james = {
name: 'James',
height: `5'10"`,
weight: 185,
};
const iterator = Object.entries(james)[Symbol.iterator]();
console.log(iterator.next()[1]); // 'James'
console.log(iterator.next()[1]); // 5'10
console.log(iterator.next()[1]); // 185
甚至
const james = {
name: 'James',
height: `5'10"`,
weight: 185,
};
for (const value of Object.values(james)) {
console.log(value);
}