本文共 1235 字,大约阅读时间需要 4 分钟。
for in和for of是JavaScript中用于遍历数据的两种不同方法,分别在ES5和ES6标准中首次引入。
for in方法用于遍历对象的属性。它会将所有可枚举的属性返回,但需要注意的是,这些属性可能包括从原型链上继承的属性。例如:
let obj = { a: 1 };let iterable = [3, 5, 7];iterable.foo = "hello";console.log(iterable.foo); // "hello"console.log(iterable.arrCustom); // 也会返回arrCustom吗?是的,因为它从数组的原型链中继承了这个属性。
while for of方法用于遍历具有Iterator接口的数据结构。这种数据结构如Array、Map、Set、String等都原生支持Iterator。它会逐个返回数据结构中的元素,这对于数组来说就是逐个数字,map中是每个键值对般的返回,但具体返回的格式取决于实现。
需要注意的是,从原型链继承的属性不会被for of遍历到。例如:
let iterable = [3, 5, 7];iterable.foo = "hello";for (let i of iterable) { console.log(i); // 3,5,7}
下面我们进一步讨论它们的区别以及如何在实际开发中使用它们。
forEach()
和 map()
遍历item
(当前项)、index
(当前索引)、input
(原始数组)三个参数。this
值都指向Window
对象。forEach()
的特点:var ary = [12, 23, 24, 42, 1];ary.forEach(function(item, index, input) { input[index] = item * 10;});console.log(ary); // 会显示改变后的数组:[120, 230, 240, 420, 10]
map()
的特点:return
赋值来创建新的数组。var res = ary.map(function(item, index, input) { return item * 10;});console.log(res); // [120, 230, 240, 420, 10]
在实际开发中,选择forEach
或map
取决于你是否需要修改原数组或是否需要返回一个新数组。forEach
适合执行异步操作或只要遍历,而map
适合生成新数组或依赖于回调函数的返回值。
通过这些方法,我们可以对数组进行丰富的操作,同时保持代码的简洁和可读性。
转载地址:http://oitrz.baihongyu.com/