用for of遍历对象有什么好处?写这么多代码,每个属性都要指定出来。如果对象的属性很多,这么遍历就太麻烦了。
来源:2-11 编程练习
电磁护盾
2021-09-25 07:54:53
<!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 } // 在此补充代码 // console.log(obj['length']); // console.log(obj['0']); // console.log(obj.sex); 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'], done: false }; }else { return { value: undefined, done: true }; } } } } for(const item of obj){ // xm // male // 2 console.log(item); } </script> </body> </html>
1回答
同学你好,代码实现效果可以。
当前编程是为了让同学们练习将对象变为可遍历对象,实际开发中用for in遍历对象较多,一般不用for of ,不要担心哦。
祝学习愉快!
相似问题