使用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之前,要实现同样的效果,我们需要使用更多的代码。该技巧适用于包含基本类型的数组:undefinednullbooleanstringnumber。如果数组中包含了一个object,function或其他数组,那就需要使用另一种方法。

除了上面的方法之外,还可以使用Array.from(new Set())来实现:

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]

 

过滤并排序字符串列表


你可能有一个很多名字组成的列表,需要过滤掉重复的名字并按字母表将其排序。

在我们的例子里准备用不同版本语言的JavaScript 保留字的列表,但是你能发现,有很多重复的关键字而且它们并没有按字母表顺序排列。所以这是一个完美的字符串列表(数组)来测试我们的JavaScript小知识。

var keywords = ['do', 'if', 'in', 'for', 'new', 'try', 'var', 'case', 'else', 'enum', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'delete', 'export', 'import', 'return', 'switch', 'typeof', 'default', 'extends', 'finally', 'continue', 'debugger', 'function', 'do', 'if', 'in', 'for', 'int', 'new', 'try', 'var', 'byte', 'case', 'char', 'else', 'enum', 'goto', 'long', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'final', 'float', 'short', 'super', 'throw', 'while', 'delete', 'double', 'export', 'import', 'native', 'public', 'return', 'static', 'switch', 'throws', 'typeof', 'boolean', 'default', 'extends', 'finally', 'package', 'private', 'abstract', 'continue', 'debugger', 'function', 'volatile', 'interface', 'protected', 'transient', 'implements', 'instanceof', 'synchronized', 'do', 'if', 'in', 'for', 'let', 'new', 'try', 'var', 'case', 'else', 'enum', 'eval', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'yield', 'delete', 'export', 'import', 'public', 'return', 'static', 'switch', 'typeof', 'default', 'extends', 'finally', 'package', 'private', 'continue', 'debugger', 'function', 'arguments', 'interface', 'protected', 'implements', 'instanceof', 'do', 'if', 'in', 'for', 'let', 'new', 'try', 'var', 'case', 'else', 'enum', 'eval', 'null', 'this', 'true', 'void', 'with', 'await', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'yield', 'delete', 'export', 'import', 'public', 'return', 'static', 'switch', 'typeof', 'default', 'extends', 'finally', 'package', 'private', 'continue', 'debugger', 'function', 'arguments', 'interface', 'protected', 'implements', 'instanceof'];

因为我们不想改变我们的原始列表,所以我们准备用高阶函数叫做filter,它将基于我们传递的回调方法返回一个新的过滤后的数组。回调方法将比较当前关键字在原始列表里的索引和新列表中的索引,仅当索引匹配时将当前关键字push到新数组。

最后我们准备使用sort方法排序过滤后的列表,sort只接受一个比较方法作为参数,并返回按字母表排序后的列表。

在ES6下使用箭头函数看起来更简单:

const filteredAndSortedKeywords = keywords 
    .filter((keyword, index) => keywords.lastIndexOf(keyword) === index) 
    .sort((a, b) => a < b ? -1 : 1);

这是最后过滤和排序后的JavaScript保留字列表:

console.log(filteredAndSortedKeywords); 
> Result: ['abstract', 'arguments', 'await', 'boolean', 'break', 'byte', 'case', 'catch', 'char', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'double', 'else', 'enum', 'eval', 'export', 'extends', 'false', 'final', 'finally', 'float', 'for', 'function', 'goto', 'if', 'implements', 'import', 'in', 'instanceof', 'int', 'interface', 'let', 'long', 'native', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'short', 'static', 'super', 'switch', 'synchronized', 'this', 'throw', 'throws', 'transient', 'true', 'try', 'typeof', 'var', 'void', 'volatile', 'while', 'with', 'yield']

清空数组


如果你定义了一个数组,然后你想清空它。 通常,你会这样做:

let array = [1, 2, 3, 4]; 
function emptyArray() { 
    array = []; 
} 
emptyArray();

但是,这有一个效率更高的方法来清空数组。 你可以这样写:

let array = [1, 2, 3, 4]; 
function emptyArray() { 
    array.length = 0; 
} 
emptyArray();

 

拍平多维数组


使用...运算符,将多维数组拍平:

const arr = [1, [2, '大漠'], 3, ['blog', '1', 2, 3]] 
const flatArray = [].concat(...arr) 

console.log(flatArray) 
> Result: (8) [1, 2, "大漠", 3, "blog", "1", 2, 3]

不过上面的方法只适用于二维数组。不过通过递归调用,可以使用它适用于二维以下的数组:

function flattenArray(arr) { 
    const flattened = [].concat(...arr); 
    return flattened.some(item => Array.isArray(item)) ? flattenArray(flattened) : flattened; 
} 

const array = [1, [2, '大漠'], 3, [['blog', '1'], 2, 3]] 
const flatArr = flattenArray(array) 
console.log(flatArr) 
> Result: (8) [1, 2, "大漠", 3, "blog", "1", 2, 3]

从数组中获取最大值和最小值


可以使用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


原文: https://www.w3cplus.com/javascript/javascript-tips.html © w3cplus.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值