1.Array.from()方法就是将一个对象转换成一个真正的数组的方法;比如
let json= {
0: '张三',
1: '美女',
2: ['李四','女','漂亮'],
'length': 3
}
let arr = Array.from(json)
console.log(json) // ['张三','美女',['李四','女','漂亮']]
Array.from还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组。如下:
1
2
3
let arr = [12,45,97,9797,564,134,45642]
let set = new Set(arr)
console.log(Array.from(set, item => item + 1)) // [ 13, 46, 98, 9798, 565, 135, 45643 ]
将字符串转换为数组:
1
2
let str = 'hello world!';
console.log(Array.from(str)) // ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]
2.reduce为数组中每一个元素依次执行回调函数比
arr.reduce(callback, [initialValue])
callback (执行数组中每个值的函数,包含四个参数) 1、previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue)) 2、currentValue (数组中当前被处理的元素) 3、index (当前元素在数组中的索引) 4、array (调用 reduce 的数组) initialValue (作为第一次调用 callback 的第一个参数。)详细解释https://www.jianshu.com/p/e375ba1cfc47