for…of特殊点小记
for…of循环可以使用的范围包括数组、Set和Map结构、某些类似数组的对象(比如arguments对象、DOM NodeList对象)、后文的Generator对象,以及字符串。
1.使用
for…of循环内部调用的是数据结构的Symbol.iterator方法。
1.1 字符串
for…of可遍历字符串,如:
1 2 3 4 5 6 7 8 9
| let str = 'abcd'; for (let i of str) { console.log(i); }
|
1.2 Map
for…of 循环将为每次迭代返回一个 key-value(键值) 数组
1 2 3 4 5 6 7 8
| let iterable = new Map([['one', 1], ['two', 2]]);
for (let [key, value] of iterable) { console.log(`${key}: ${value}`); }
|
2.输出
2.1 不会输出属性及方法
for-in:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| let arr = [1, 2, 3]; arr.param1 = 'value1'; arr.func1 = function () {}; Array.prototype.func2 = function () {};
for (let i in arr) { console.log(i + ':' + arr[i]); }
|
for-or:
1 2 3 4 5 6 7 8 9 10 11 12
| let arr = [1, 2, 3]; arr.param1 = 'value1'; arr.func1 = function () {}; Array.prototype.func2 = function () {};
for (let item of arr) { console.log(item); }
|
参考资料:
Author
My name is Micheal Wayne and this is my blog.
I am a front-end software engineer.
Contact: michealwayne@163.com