1const fruits = ['', '', '', '', 'apple']; 2console.log(...fruits); // apple
1// 复制数组 2let arr = [1, 2, 3]; 3let arrCopy = [ ...arr ]; 4// 复制对象 5let user = {name : "John", age : 20 } 6let userCopy = {...user}
注意: 这里执行的是浅拷贝
1// 合并数组 2let arr1 = [1, 2, 3] 3let arr2 = [4, 5, 6] 4let arr = [...arr1, ...arr2] 5console.log(arr); // [1, 2, 3, 4, 5, 6] 6// 合并对象 7let obj1 = { 8 name: 'Jack' 9} 10let obj2 = { 11 age: 18 12} 13let obj = {...obj1, ...obj2} 14console.log(obj) // {name: 'Jack', age: 18}
1function sum(a, b) { 2 return a+b; 3} 4let num = [1,2]; 5sum(...num); 6// 与 math 函数一起使用 7let num = [5,9,3,5,7]; 8Math.min(...num); // 3 9Math.max(...num); // 9
1// 数组中 2let [melon, ...fruits ] = ['melon', 'apple', 'banana', 'orange']; 3console.log(melon); // melon 4console.log(fruits); // ['apple', 'banana', 'orange'] 5// 对象中 6let user = {name : "Jack", age: 20, salary: '20K', job : "码畜" }; 7let { name, age, ...details } = user; 8console.log(name); // Jack 9console.log(details); // {salary: '20K', job : '码畜'};
1// 数组去重 2let arr = [1, 2, 1, 2, 3] 3// 我们原来的操作: 4// let list = Array.from(new Set(arr)) 5let list = [...new Set(arr)] 6console.log(list) // [1, 2, 3]
array.filter(function(currentValue,index,arr), thisValue) currentValue: 必选,当前元素的值 index:可选,当前元素的下标 arr: 可选,当前数组 thisValue:可选,执行 callback 时,用于 this 的值
其作用是对数组进行过滤,不改变原数组
1const arr = ['apple', 'strawberry', 'banana', 'pear', 'apple', 'orange', 'orange', 'strawberry'] 2const list = arr.filter((element, index, self)=> self.indexOf(element) === index) 3console.log(list) // ["apple", "strawberry", "banana", "pear", "orange"]
undefined null NaN 0 '' (空字符) false
删除数组中的虚值我们只需要:
myArray.filter(Boolean)