1数组中删除重复
let arr = [1,2,4,3,6,4] Array.from(new Set(arr)) // es6中 .from()[1,2,4,3,6] [...new Set(arr)] // 扩展运算符[1,2,4,3,6]
2替换数组中指定的值
arr .splice(1,3,7,8,9) // [7, 8, 9] arr // [1, 7, 8, 9, 6, 4]
3数组映射
let mapValue = [ { name: '山东', value: 22 }, { name: '北京', value: 23 }, { name: '上海', value: 24 } ] mapValue.map(item=> {item.name}); // map Array.from(mapValue, ({name}) => name); // .from()
4清空数组
arr.length = 0 // arr =[]
5将数组转化为对象
let obj = {...arr } // {0: 1, 1: 7, 2: 8, 3: 9, 4: 6, 5: 4}
6合并数组
let arr2 =['one','two',2] // [1, 2, 4, 3, 6, 4, "one", "two"] [...arr2,...arr] // ["one", "two", 1, 2, 4, 3, 6, 4]
7两个数组的交集
首先保证数组中的值不重复,然后利用.filter和.includes方法即可
let numOne = [0, 2, 4, 6, 8, 8]; let numTwo = [1, 2, 3, 4, 5, 6]; [...new Set(numOne)].filter(item => numTwo.includes(item))
8从数组中删除假值
首先在Javascript中,假值包括false、0、''、null、NaN、undefined
let mixArrs =[null,3,undefined,true,''] mixArrs.filter(Boolean); // [3, true]
9颠倒数组中元素的顺序
let mixArrs =[null,3,undefined,true,''] mixArrs.reverse() // ["", true, undefined, 3, null]
10数组中的所有值求和
let array = [1, 2, 3, 4, 5] eval(array.join("+")) ; // 15 array.reduce((x, y) => x + y); // 15
11使用固定值填充数组
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.fill("Runoob"); //Runoob,Runoob,Runoob,Runoob let newArr = new Array(6).fill('2'); // ["2", "2", "2", "2", "2", "2"]