前言
ES8 中新增了一个 Array.values() 方法,该方法会返回一个迭代器对象,包含数组中每个元素的值。虽然该方法在处理数组时十分方便,但是在某些情况下,使用该方法可能会遇到问题。本文将介绍在使用 Array.values() 方法时可能出现的问题,并提供解决方案。
问题
在大多数情况下,使用 Array.values() 方法获取数组的值都很顺利。但是当数组中有空、未定义或 null 的元素时,该方法就会出现问题。下面的示例代码演示了这个问题:
const arr = [1, 2, , 4, undefined, null]; console.log(Array.from(arr)); // [1, 2, undefined, 4, undefined, null] console.log([...arr]); // [1, 2, undefined, 4, undefined, null] console.log(Array.prototype.slice.call(arr)); // [1, 2, undefined, 4, undefined, null] console.log([...arr.values()]); // [1, 2, 4, undefined, null]
可以看到,Array.values() 方法没有返回数组中undefined之后的元素,这是因为迭代器会在遇到第一个空、未定义或 null 的元素时停止迭代。这个问题可能会导致在处理数组时出现错误,因此需要解决。
解决方案
- 使用 Array.prototype.filter() 方法
使用 Array.prototype.filter() 方法可以很容易地过滤出所有非空元素。下面的示例代码演示了如何使用该方法:
const arr = [1, 2, , 4, undefined, null]; const filteredArr = arr.filter(el => el !== undefined && el !== null); console.log([...filteredArr.values()]); // [1, 2, 4]
- 使用 for...of 循环
使用 for...of 循环可以遍历数组中所有的元素,包括空、未定义或 null 的元素。下面的示例代码演示了如何使用该方法:
const arr = [1, 2, , 4, undefined, null]; const values = []; for (const val of arr) { values.push(val); } console.log(values); // [1, 2, undefined, 4, undefined, null]
- 使用 Array.prototype.concat() 方法
使用 Array.prototype.concat() 方法可以将数组中所有元素合并到一个新数组中,包括空、未定义或 null 的元素。下面的示例代码演示了如何使用该方法:
const arr = [1, 2, , 4, undefined, null]; const values = arr.concat(); console.log([...values.values()]); // [1, 2, undefined, 4, undefined, null]
结论
在 ES8 中,Array.values() 方法可以很方便地获取数组中的值,但是在数组中存在空、未定义或 null 的元素时,该方法可能会出现问题。因此,需要采用上述方法中的一种来解决这个问题。对于开发者而言,需要有意识地避免在数组中使用空、未定义或 null 的元素,以免出现问题。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/6702f71ed91dce0dc849531a