js 数组方法的妙用
删除数组的重复项
var arr = [1, 2, 5, 6, 2];
方法一: let result = Array.from(new Set(arr))
方法二: let result = [...new Set(arr)]
替换数组中的特定值
var arr = ['a1', 'a2', 'a3', 'a4']
arr.splite(0, 2, 'b1', 'b2')
console.log(arr) // ['b1', 'b2', 'a3', 'a4']
Array.from 达到 .map 的效果
var arr = [ {a: 1}, {a: 2}, { a: 3}];
var result = Array.from(arr, (item) => { return item.a});
console.log(result) // [1, 2, 3]
置空数组
var arr = [1, 3, 2, 4]
arr.length = 0
将数组转换为对象
var arr = [1, 2, 3]
let result = {...arr}
用数据填充数组
let result = new Array.fill('1')
求两个数组的交集
var arr1= [1, 4, 6, 7];
var arr2 = [6, 8, 10, 1];
var result = [...new Set(arr1)].filter(item => arr2.includes(item))
从数组中删除虚值
var arr = [1, 0, 'a', false, 0, 'a', undefined]
var result = arr.filter(Boolean)
从数组中获取随机值
var arr = [1, 0, 'a', false, 0, 'a', undefined];
var result = arr[parseInt(Math.random()*arr.length)];
console.log(result)
对数组中的所有值求和
var arr1= [1, 4, 6, 7];
var sum = arr1.reduce((x, y) => x + y)