您的位置:首页 > 其它

for...of 与 for...in 区别

2018-03-23 11:07 127 查看

一、for...of

1.定义

for...of 语句遍历可迭代对象(包括数组、Set 和 Map 结构、arguments 对象、DOM NodeList 对象、字符串等)。

2.语法

for (variable of iterable) {
//statements
}

3.示例

<ul>
<li>mazey</li>
<li>luna</li>
<li>cherrie</li>
</ul>
<script>
// 数组
let arr = ['mazey', 'luna', 'cherrie'];
for (let v of arr) {
console.log(v);
}
// mazey luna cherrie

// 字符串
let str = 'mlc';
for (let v of str) {
console.log(v);
}
// m l c

// 类数组对象
let obj = {
0: 'mazey',
1: 'luna',
2: 'cherrie',
length: 3
};
// 需使用Array.from转换成可迭代对象
for (let v of Array.from(obj)) {
console.log(v);
}
// mazey luna cherrie

// Set
let s = new Set(['mazey', 'luna', 'cherrie']);
for (let v of s) {
console.log(v);
}
// mazey luna cherrie

// Map
let m = new Map([
['name0', 'mazey'],
['name1', 'luna'],
['name2', 'cherrie']
]);
for (let [i, v] of m) {
console.log(v);
}
// mazey luna cherrie

// DOM NodeList
let domList = document.querySelectorAll('li');
for (let v of domList) {
console.log(v.innerText);
}
// mazey luna cherrie
</script>

二、for...of 与 for...in 区别

1.for...in 遍历键名,for...of 遍历键值

let arr = ['mazey', 'luna', 'cherrie'];
for (let k in arr) {
console.log(k);
}
// 0 1 2
for (let v of arr) {
console.log(v);
}
// mazey luna cherrie

2.for...in 会把对象上手动添加的属性和原型上的属性暴露出来

let obj = {
0: 'mazey',
1: 'luna',
2: 'cherrie',
length: 3
};
obj.name = 'objName';
for (let k in obj) {
console.log(k);
}
// 0 1 2 length name
for (let v of Array.from(obj)) {
console.log(v);
}
// mazey luna cherrie

三、for...of 其它优点

1.相对于数组自带的 forEach 方法,for...of 可以与 break、continue 和 return 配合使用。
2.正确识别32位 UTF-16 字符。

for…of 与 for…in 区别

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: