1. 程式人生 > >數組的查找和排序方法

數組的查找和排序方法

索引 yellow 連接 () 反轉數組 lac 總結 自定義函數 ons

數組的排序方法:
reverse() 反轉數組元素的順序。
sort() 對數組的元素進行排序。 可以不寫,也可以傳一個自定義函數用來排序。

var = [2, 14, 3, 37, 5, 40];
console.log( .sort()); // [14, 2, 3, 37, 40, 5]
console.log( .reverse()); // [5, 40, 37, 3, 2, 14]

var = [5, 21, 19, 8, 3];
function sortFn(a ,b ) {
return a> b;
}
console.sort(sortFn );
console.log(arr ); // [3, 5, 8, 19, 21]

箭頭函數:
var = [5, 21, 19, 8, 3];
arr.sort( (a , b) => a> b);
console.log( arr); // [3, 5, 8, 19, 21]

總結:
返回值 a > b ,數組按從小到大的順序排列。
返回值 a < b ,數組按從大到小的順序排列。

連接方法:
concat() 連接兩個或更多的數組,並返回結果。 需要合並的數組名或者數組元素

var = [ "red", "blue", "green" ];
var = .concat( "yellow", [ "black", "pink" ] );
console.log( );// red,blue,green,yellow,black,pink

位置方法:
indexOf() 從數組頭部開始查找指定元素,返回元素在數組中的索引值。
lastIndexOf() 從數組末尾開始向前查找指定元素,返回元素在數組中的索引值。

var = ["a", "b", "c", "d", "e", "c"];
console.log(arr .indexOf("c")); // 2
console.log( arr.lastIndexOf("c")); // 5

註意:如果查找的元素在數組中不存在,則返回 -1。

數組的查找和排序方法