被低估的数组方法
我们每天在编程时都会用到数组,它可能是使用最广泛的数据结构。JavaScript 开发者可能都依赖它许多强大的数组方法,例如、 、 、.map
等等.filter
。.find
事实上,JS 中的数组原型还有许多其他非常有用的方法,其中一些方法几乎不为大多数开发人员所知,所以让我们开始吧:.some
.every
.reduce
copyWithin(target, start?, end?)
🙇🏻♂️ 注意,它将修改原始数组,而不是返回一个新数组
这个方法会将元素复制到target
从start
位置到的位置end
,听起来有点令人困惑吧?让我们看一些代码
let array = [1,2,3,4,5];
console.log(array.copyWithin(3, 1, 3)) // [1, 2, 3, 2, 3]
那么这里到底发生了什么?取出从 index1
到 index的元素3
,并将它们从 index 开始放置3
。让我们看另一个例子:
let array = [1,2,3,4,5,6,7,8,9,10];
console.log(array.copyWithin(0,5)) // [6, 7, 8, 9, 10, 6, 7, 8, 9, 10]
因此,这里我们将从 5 开始直到数组末尾的元素从 0 开始放置。换句话说,我们可以这样理解:
array.copyWithin(Where the elements must go, where should it start copying from, where should stop to copy);
让我们再看看它的一个技巧:
let array = [1, 2, 3, 4, 5];
array.copyWithin(2); // [1, 2, 1, 2, 3]
// If the target is negative it will copy starting from reverse
array = [1, 2, 3, 4, 5];
array.copyWithin(-2); // [1, 2, 3, 1, 2]
lastIndexOf(searchedElement, toIndex?)
这个特别有用,我们先看一个简单的例子:
const fruits = [
'apple',
'banana',
'strawberry',
'blueberry',
'orange',
'blueberry',
'pineapple',
];
// It will log the index of the last occurency of 'blueberry'
console.log(fruits.lastIndexOf('blueberry')); // 5
在某些时刻,您可能只想在某个特定索引之前查找最后一次出现的内容,例如:
const fruits = [
'apple',
'banana',
'strawberry',
'blueberry',
'orange',
'blueberry',
'pineapple',
];
// You only wanted the last index of 'blueberry' if it was
// between the 3 first elements
console.log(fruits.lastIndexOf('blueberry', 2)); // -1
但是当你有更复杂的对象并将其与其他数组方法结合使用时,此方法会变得更加有趣。让我们来看看:
const persons = [
{ name: 'Charles', age: 26 },
{ name: 'Marcos', age: 31 },
{ name: 'Jane', age: 22 },
{ name: 'Anton', age: 22 },
{ name: 'Eduardo', age: 22 },
{ name: 'Paula', age: 26 },
];
// We want to find the index of the last person
// who is 22 years old,
// unfotunately lastIndexOf doesn't accept a callback
// so we gonna transform the array in array of ages that
// match the index with the objects and find the last
// occurence of 22
persons
.map(person => person.age)
.lastIndexOf(22); // 4
reduceRight(callBack, initialValue?)
这个有点有趣,而且很容易理解,签名与原始方法完全相同reduce
,其行为也完全相同,只有细微的差别:不是从左到右迭代,而是从右到左迭代(正如名称所表明的那样)所以让我们看一些简单的例子。
const numbers = ["1", "2", "3", "4", "5"];
console.log(
numbers.reduce((acc, curr) => {
return acc + curr;
}, "")
); // "12345"
console.log(
numbers.reduceRight((acc, curr) => {
return acc + curr;
}, "")
); // "54321"
当你想从左到右表达某些东西但从右到左评估它时,这种方法非常方便,让我们看一个更复杂的例子:
const add10 = n => n + 10;
const divideBy2 = n => n / 2;
const commands = [divideBy2, add10];
console.log(
commands.reduce((acc, curr) => {
return curr(acc);
}, 100)
); // 60
console.log(
commands.reduceRight((acc, curr) => {
return curr(acc);
}, 100)
); // 55
希望这篇文章能给你带来一些新意,让你对 JavaScript 数组至少有一点了解。欢迎在评论区留言,告诉我你觉得这篇文章怎么样 :)
文章来源:https://dev.to/assuncaocharles/undererated-array-methods-2mdj