8.数组中常用的一些方法(整理中)
1.array.prototype.sort()
对数组进行排序,返回排序后的数组。注意:数组是原地排序。
语法:arr.sort([compareFunction])
compareFunction 可选用来指定按某种顺序进行排列的函数。如果省略,元素按照转换为的字符串的各个字符的Unicode位点进行排序。
firstEl第一个用于比较的元素。secondEl第二个用于比较的元素。
如果没有指明compareFunction,那么元素会按照转换为的字符串的诸个字符的Unicode位点进行排序。例如 "Banana" 会被排列到 "cherry" 之前。当数字按由小到大排序时,9 出现在 80 之前,但因为(没有指明compareFunction),比较的数字会先被转换为字符串,所以在Unicode顺序上 "80" 要比 "9" 要靠前。
如果指明了compareFunction,那么数组会按照调用该函数的返回值排序。即a和b是两个将要被比较的元素:
- 如果
compareFunction(a,b)小于0,那么a会被排列到b之前;
- 如果
compareFunction(a,b)等于0,a和b的相对位置不变。备注:ECMAScript标准并不保证这一行为,而且也不是所有浏览器都会遵守(例如 Mozilla 在 2003 年之前的版本);
- 如果
compareFunction(a,b)大于0,b会被排列到a之前。 compareFunction(a,b)必须总是对相同的输入返回相同的比较结果,否则排序的结果将是不确定的。

1 var numbers = [4, 2, 5, 1, 3]; 2 numbers.sort((a, b) => a - b); 3 console.log(numbers); 4 5 // [1, 2, 3, 4, 5]
2.array.prototype.includes()
includes()方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回true,否则返回false。
1 [1, 2, NaN].includes(NaN); // true
3.Array.prototype.indexOf()
indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。
1 console.log([1, 2, NaN].indexOf(NaN)) //-1
注意includes和indexOf两者在NaN检测上的区别,前者可以检测出来,而后者不可以。
4.Array.prototype.find()
find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回undefind。
arr.find(callback[, thisArg])
1 const array1 = [5, 12, 8, 130, 44]; 2 3 const found = array1.find(element => element > 10);
5.Array.prototype.forEach()
arr.forEach(callback(currentValue [, index [, array]])[, thisArg])
注意:除了抛出异常以外,没有办法中止或跳出forEach()循环。如果你需要中止或跳出循环,forEach()方法不是应当使用的工具。
6.Array.prototype.shift()
shift() 方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。
7.Array.prototype.unshift()
unshift() 方法将一个或多个元素添加到数组的开头,并返回该数组的新长度(该方法修改原有数组)。
以下方法会改变原数组:
push()
pop()
shift()
unshift()
splice()
sort()
reverse()
以下方法不会改变原数组:
filter()
concat()
slice()
map()
浙公网安备 33010602011771号