原文地址:https://dev.to/bhagatparwinder/array-instance-methods-ii-d5l
实例方法是存在于 Array 的 prototype 上的,这是第三篇关于 Array 方法的文章。
lastIndexOf
lastIndexOf 是为你找到指定元素最后出现的下标位置,若没有找到则返回 -1 。它还接受第二个参数 fromIndex
来指定向后查找的下标。
const numbers = [1, 22, 123, 0, 15, 9, 88, 123, 0, 45];
console.log(numbers.lastIndexOf(2)); // -1
console.log(numbers.lastIndexOf(22)); // 1
console.log(numbers.lastIndexOf(0)); // 8
console.log(numbers.lastIndexOf(123, 4)); // 2
console.log(numbers.lastIndexOf(0, 6)); // 3
console.log(numbers.lastIndexOf(1, 1)); // 0
个人添加:
pop
pop 方法移出数组的最后一个元素并返回。
const numbers = [1, 22, 123, 0, 15, 9, 88, 123, 0, 45];
console.log(numbers.pop()); // 45
console.log(numbers.pop()); // 0
console.log(numbers.pop()); // 123
console.log(numbers.pop()); // 88
reverse
reverse 方法原地翻转数组,然后返回。注意:此方法更改原始数组类似 sort。
const original = ['one', 'two', 'three'];
const reversed = original.reverse();
console.log(reversed); // ["three", "two", "one"]
console.log(original); // ["three", "two", "one"]
shift
shift 方法类似 pop,shift 移出头部的元素,而 pop 是移出尾部元素。它们都返回移除的元素。
const original = [1, 2, 3]
const firstRemoved = original.shift();
console.log(original); // [2, 3]
console.log(firstRemoved); // 1
some
some 方法用来检测至少有一个元素满足回调函数或测试方法。
const array = [1, 2, 3, 4, 5];
const even = (element) => element % 2 === 0; // checks whether an element is even
const greaterThanTen = (element) => element > 10; // checks whether an element is greater than 10
console.log(array.some(even)); // true
console.log(array.some(greaterThanTen)); // false
sort
sort 方法默认按升序(元素转为字符串,比较它们的 UTF-16 代码单元值的序列)排列数组。
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months); // ["Dec", "Feb", "Jan", "March"]
const numbers = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1); // [1, 100000, 21, 30, 4]
注意,最后一个例子 100000 怎么排到 21 前面的,那是因为在排序前先转换为字符串然后再比较。
sort 方法允许传递一个回调函数来自定义比较方法。
const numbers = [1, 30, 4, 21, 100000];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers); // [ 1, 4, 21, 30, 100000 ]
这个例子就返回了你想要的排序后的数组。
toString
toString 返回数组元素组合成的字符串。
const sample = [1, 2, "Parwinder", true, "Hello", 78];
console.log(sample.toString()); // 1,2,Parwinder,true,Hello,78
unshift
unshift 类似 push 方法,push 向数组末尾添加元素而 unshift 向数组头部添加元素。它们都返回数组的长度而不是新的数组。
const numbers = [1, 2, 3];
console.log(numbers.unshift(4, 5, 6)); // 6
console.log(numbers); // [ 4, 5, 6, 1, 2, 3 ]
到此就是我要介绍的一些常用数组方法,还有一些不常用的请查阅:MDN。