for/in 语句 与 for/of语句
1、or/in 语句
for/in 语句用于循环对象属性。
循环中的代码每执行一次,就会对数组的元素或者对象的属性进行一次操作。
for-in循环实际是为循环”enumerable“对象而设计的。
参数值
| 参数 | 描述 |
|---|---|
| var | 必须。指定的变量可以是数组元素,也可以是对象的属性。 |
| object | 必须。指定迭代的的对象。 |
循环结构 for/in 语句 - <script>
- {
- // for/in 语句 用于循环对象属性。 每一次取到的属性,都要存储在text变量中
- let person = {fname:'tim', lname:'yiyi', age:15}
-
- // 定义text变量的目的,用了存储 对象中的属性
- let text = "";
- // 定义索引变量名
- let x ;
- for(x in person){
- console.log(x);
- console.log(person[x]);
-
- text += person[x]+" ";
- // text += x + ":" + person[x]+" ";
-
- // text +='person.'+ x + "=" + person[x]+"
"; - }
- console.log('查看: '+text);
- document.write('查看: '+text);
- }
- script>
预览效果:

2、for/of语句
for/of 在 2015 年被添加到 JavaScript (ES6)。
for-of的语法看起来跟for-in很相似,但它的功能却丰富的多,它能循环很多东西
- // for/of 遍历数组对象
- {
- var arr = [
- { name:'nick', age:18 },
- { name:'freddy', age:24 },
- { name:'mike', age:26 },
- { name:'james', age:34 }
- ];
- // 对象中的属性的获取方式 对象名 属性名
- for(let item of arr){
- console.log(item.name, item.age);
- }
- }
预览效果:
