arr .forEach(callback(currentValue [,index [,array]]) [,thisArg ])
callback在每个元素上执行的功能。它接受一到三个参数:
currentValue数组中正在处理的当前元素。
index可选的currentValue数组中的索引。
array可选的该数组forEach()被调用。
thisArg可选的this执行时用作的值callback。
展平数组
function flatten(arr) {
const result = []
arr.forEach((i) => {
if (Array.isArray(i)) {
result.push(...flatten(i))
} else {
result.push(i)
}
})
return result
}
// Usage
const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]]
flatten(nested) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h63435.shtml