一,會改變原數組javascript
1.移除數組末尾最後一項.pop(),返回刪除的元素 若是你在一個空數組上調用 pop(),它返回 undefined
let word = ['a', 'b', 'c', 'd'];java
let newArr = word.pop(); console.log(word); //['a', 'b', 'c'] console.log(newArr); //d let nullArr = []; console.log(nullArr.pop()); //undefined 2.在數組末尾添加一個或多個元素.push(),返回修改後數組長度
[javascript] view plain copy數組
let word = ['a', 'b', 'c', 'd']; let newArr = word.push('e','f'); console.log(word); //['a', 'b', 'c', 'd', 'e', 'f'] console.log(newArr); //6 3.移除數組第一項.shift(),返回移除的元素
[javascript] view plain copyapp
let word = ['a', 'b', 'c', 'd']; let newArr = word.shift(); console.log(word); //['b', 'c', 'd'] console.log(newArr); //a 4.在數組頭部添加一個或多個元素.unshift(),返回修改後數組長度
[javascript] view plain copyui
let word = ['a', 'b', 'c', 'd']; let newArr = word.unshift('11','22'); console.log(word); //['11', '22', 'a', 'b', 'c', 'd'] console.log(newArr); //6 5.對數組元素排序.sort(),返回排序後的數組 默認排序順序是根據字符串Unicode碼點
[javascript] view plain copy指針
let fruit = ['cherries', 'apples', 'bananas']; console.log(fruit.sort()); // ['apples', 'bananas', 'cherries'] let scores = [1, 10, 21, 2]; console.log(scores.sort()); // [1, 10, 2, 21] // 注意10在2以前, // 由於在 Unicode 指針順序中"10"在"2"以前 let things = ['word', 'Word', '1 Word', '2 Words']; console.log(things.sort()); // ['1 Word', '2 Words', 'Word', 'word'] // 在Unicode中, 數字在大寫字母以前, // 大寫字母在小寫字母以前. function compare(a, b) { if(a < b) { return -1; }else if(a > b) { return 1; }else { return 0; } } let num = [1, 10, 21, 2]; console.log(num.sort(compare)); //[1, 2, 10, 21] 6.顛倒數組元素.reverse(),返回顛倒後的數組
[javascript] view plain copycode
let word = ["a", "b", "c", "d"]; let newArr = word.reverse(); console.log(word); //["d", "c", "b", "a"] console.log(newArr); //["d", "c", "b", "a"] 7.刪除或插入元素.splice(),返回數組刪除的項,沒有刪除的項,返回空數組
[javascript] view plain copy排序
var word = ['a', 'b', 'c', 'd']; //刪除,前閉後開 var newArr = word.splice(0,2); console.log(word); //["c", "d"] console.log(newArr); //["a", "b"] //插入,當前數組索引1處插入hello var newArr = word.splice(1,0,'hello'); console.log(word); //["c", "hello", "d"] console.log(newArr); //[] //替換 var newArr = word.splice(1,1,'world'); console.log(word); //["c", "world", "d"] console.log(newArr); //["hello"]