ES6提供了几种简洁的数组去重的方法,但该方法并不适合处理非基本类型的数组。对于基本类型的数组去重,可使用... new Set()
来过滤掉数组中重复的值,建立一个只有惟一值的新数组。数组
const array = [1, 1, 2, 3, 5, 5, 1] const uniqueArray = [...new Set(array)]; console.log(uniqueArray); > Result:(4) [1, 2, 3, 5]
这是ES6中的新特性,在ES6以前,要实现一样的效果,咱们须要使用更多的代码。该技巧适用于包含基本类型的数组:undefined
、null
、boolean
、string
和number
。若是数组中包含了一个object
,function
或其余数组,那就须要使用另外一种方法。app
除了上面的方法以外,还可使用Array.from(new Set())
来实现:性能
const array = [1, 1, 2, 3, 5, 5, 1] Array.from(new Set(array)) > Result:(4) [1, 2, 3, 5]
另外,还可使用Array
的.filter
及indexOf()
来实现:code
const array = [1, 1, 2, 3, 5, 5, 1] array.filter((arr, index) => array.indexOf(arr) === index) > Result:(4) [1, 2, 3, 5]
注意,indexOf()
方法将返回数组中第一个出现的数组项。这就是为何咱们能够在每次迭代中将indexOf()
方法返回的索引与当索索引进行比较,以肯定当前项是否重复。索引
在处理网格结构时,若是原始数据每行的长度不相等,就须要从新建立该数据。为了确保每行的数据长度相等,可使用Array.fill
来处理:string
let array = Array(5).fill(''); console.log(array); > Result: (5) ["", "", "", "", ""]
不使用Array.map
来映射数组值的方法。it
const array = [ { name: '大漠', email: 'w3cplus@hotmail.com' }, { name: 'Airen', email: 'airen@gmail.com' }] const name = Array.from(array, ({ name }) => name) > Result: (2) ["大漠", "Airen"]
若是你想从数组末尾删除值(删除数组中的最后一项),有比使用splice()
更快的替代方法。io
例如,你知道原始数组的大小,能够从新定义数组的length
属性的值,就能够实现从数组末尾删除值:console
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] console.log(array.length) > Result: 10 array.length = 4 console.log(array) > Result: (4) [0, 1, 2, 3]
这是一个特别简洁的解决方案。可是,slice()
方法运行更快,性能更好:ast
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; array = array.slice(0, 4); console.log(array); > Result: [0, 1, 2, 3]
若是你想过滤数组中的falsy值,好比0
、undefined
、null
、false
,那么能够经过map
和filter
方法实现:
const array = [0, 1, '0', '1', '大漠', 'w3cplus.com', undefined, true, false, null, 'undefined', 'null', NaN, 'NaN', '1' + 0] array.map(item => { return item }).filter(Boolean) > Result: (10) [1, "0", "1", "大漠", "w3cplus.com", true, "undefined", "null", "NaN", "10"]
数组的slice()
取值为正值时,从数组的开始处截取数组的项,若是取值为负整数时,能够从数组末属开始获取数组项。
let array = [1, 2, 3, 4, 5, 6, 7] const firstArrayVal = array.slice(0, 1) > Result: [1] const lastArrayVal = array.slice(-1) > Result: [7] console.log(array.slice(1)) > Result: (6) [2, 3, 4, 5, 6, 7] console.log(array.slice(array.length)) > Result: []
正如上面示例所示,使用array.slice(-1)
获取数组的最后一项,除此以外还可使用下面的方式来获取数组的最后一项:
console.log(array.slice(array.length - 1)) > Result: [7]
可使用Math.max
和Math.min
取出数组中的最大小值和最小值:
const numbers = [15, 80, -9, 90, -99] const maxInNumbers = Math.max.apply(Math, numbers) const minInNumbers = Math.min.apply(Math, numbers) console.log(maxInNumbers) > Result: 90 console.log(minInNumbers) > Result: -99
另外还可使用ES6的...
运算符来完成:
const numbers = [1, 2, 3, 4]; Math.max(...numbers) > Result: 4 Math.min(...numbers) > Result: 1