为什么无法全部遍历打印
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >Document</ title > </ head > < body > < script > const obj = { "0": "xm", "sex": "male", length: 2 } // 在此补充代码 obj[Symbol.iterator]=Array.prototype[Symbol.iterator]; for(const i of obj){ console.log(i) } </ script > </ body > </ html > |
问题描述:
为什么无法全部遍历打印,问题在哪?
8
收起
正在回答
1回答
同学你好,遍历的是有索引的,例如数组:
而对象中的属性名为数字的只有第一个0,所以只输出xm;不是数字的,会返回undefined值,并且length不会输出。
建议参考课程中的写法:
修改为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | const obj = { "0" : "xm" , "sex" : "male" , length: 2 }; // 在此补充代码 // obj[Symbol.iterator] = Array.prototype[Symbol.iterator]; obj[Symbol.iterator] = () => { let index = 0; return { next() { index++; if (index === 1) { return { value: obj[ "0" ], done: false , }; } else if (index === 2) { return { value: obj[ "sex" ], done: false , }; } else if (index === 3) { return { value: obj[ "length" ], }; } else { return { done: true , }; } }, }; }; for (const i of obj) { console.log(i); } |
祝学习愉快!
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧