关于javascript:JavaScript的一些小技巧

4次阅读

共计 2378 个字符,预计需要花费 6 分钟才能阅读完成。

数组去重

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 之前,要实现同样的成果,咱们须要应用更多的代码。该技巧实用于蕴含根本类型的数组:undefinednullbooleanstringnumber。如果数组中蕴含了一个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.filterindexOf() 来实现:

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 值,比方 0undefinednullfalse,那么能够通过mapfilter办法实现:

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.maxMath.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
正文完
 0