首页 > 编程语言 > JavaScript的一些小技巧分享
2021
01-08

JavaScript的一些小技巧分享

数组去重

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或其他数组,那就需要使用另一种方法。

除了上面的方法之外,还可以使用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()来实现:

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来处理

let array = Array(5).fill(''); 
console.log(array); 
> Result: (5) ["", "", "", "", ""]

数组映射

不使用Array.map来映射数组值的方法。

const array = [ 
 { 
 name: '大漠', 
 email: 'w3cplus@hotmail.com' 
 }, 
 { 
 name: 'Airen', 
 email: 'airen@gmail.com'
 }] 
 const name = Array.from(array, ({ name }) => name) 
 
 > Result: (2) ["大漠", "Airen"]

数组截断

如果你想从数组末尾删除值(删除数组中的最后一项),有比使用splice()更快的替代方法。

例如,你知道原始数组的大小,可以重新定义数组的length属性的值,就可以实现从数组末尾删除值:

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()方法运行更快,性能更好:

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值

如果你想过滤数组中的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

以上就是JavaScript的一些小技巧分享的详细内容,更多关于JavaScript 小技巧的资料请关注自学编程网其它相关文章!

编程技巧