棧方法
push方法和pop方法, 可以使數(shù)組的行為類似于棧, 先進(jìn)后出, 并且推入和彈出操作只發(fā)生在一端.
push方法
push方法可以接收一個(gè)或多個(gè)參數(shù), 把它們追加到數(shù)組末尾, 并返回修改后數(shù)組的長度.
var arr = ['a', 'b', 'c', 'd', 'e'];var temp = arr.push('f');console.info('temp: ' + temp); // temp: 6console.info(arr); // ["a", "b", "c", "d", "e", "f"]temp = arr.push('g', 'h');console.info('temp: ' + temp); // temp: 8console.info(arr); // ["a", "b", "c", "d", "e", "f", "g", "h"]合并兩個(gè)數(shù)組
我們可以通過Array.prototype.push.apply()來合并兩個(gè)數(shù)組, 示例如下:
var arr1 = ['a', 'b', 'c'], arr2 = ['x', 'y', 'z'];var temp = Array.prototype.push.apply(arr1, arr2);console.info(arr1); // ["a", "b", "c", "x", "y", "z"]console.info(arr2); // ["x", "y", "z"]console.info(temp); // 6
pop方法
pop方法是將數(shù)組的最后一項(xiàng)移除, 將數(shù)組長度減1, 并返回移除的項(xiàng).
var arr = ['a', 'b', 'c', 'd', 'e'];var temp = arr.pop();console.info('temp: ' + temp); // temp: econsole.info('length: ' + arr.length); // length: 4如果在一個(gè)空數(shù)組上使用pop方法, 則返回undefined
隊(duì)列方法
隊(duì)列的訪問規(guī)則是先進(jìn)先出, 并且隊(duì)尾添加項(xiàng), 隊(duì)頭移除項(xiàng). push方法和shift方法結(jié)合使用, 就可以像操作隊(duì)列一樣操作數(shù)組.
shift方法
shift方法將移除數(shù)組的第一項(xiàng), 將數(shù)組長度減1, 并返回移除的項(xiàng).
var arr = ['a', 'b', 'c', 'd', 'e'];var temp = arr.shift();console.info('temp: ' + temp); // temp: aconsole.info('length: ' + arr.length); // length: 4unshift方法
相反地, 還有一個(gè)unshift方法, 它的用途與shift方法相反
unshift也可以在接收一個(gè)或多個(gè)參數(shù), 把它們依次添加到數(shù)組的前端, 并返回修改后數(shù)組的長度.
var arr = ['a', 'b', 'c', 'd', 'e'];var temp = arr.unshift('x', 'y', 'z');console.info('temp: ' + temp); // temp: 8console.info(arr); // ["x", "y", "z", "a", "b", "c", "d", "e"]重排序方法
sort方法和reverse方法
sort方法和reverse方法是可以直接用來重排序的兩個(gè)方法.
其中, reverse方法是用來反轉(zhuǎn)數(shù)組的.
var arr = [1, 3, 2, 5, 4];arr.reverse();console.info(arr); // [4, 5, 2, 3, 1]
關(guān)于sort方法, 默認(rèn)情況下, 它是對數(shù)組的每一項(xiàng)進(jìn)行升序排列, 即最小的值在前面. 但sort方法會調(diào)用toString方法將每一項(xiàng)轉(zhuǎn)成字符串進(jìn)行比較(字符串通過Unicode位點(diǎn)進(jìn)行排序), 那么這種比較方案在多數(shù)情況下并不是最佳方案. 例如:
var arr = [1, 3, 2, 5, 4];arr.sort();console.info(arr); // [1, 2, 3, 4, 5]arr = [1, 5, 10, 20, 25, 30];arr.sort();console.info(arr); // [1, 10, 20, 25, 30, 5]
新聞熱點(diǎn)
疑難解答
圖片精選