pop
- 定義:刪除數(shù)組中的最后一個(gè)元素并返回該元素,此方法修改數(shù)組長度;
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop()); // "tomato"
console.log(plants); // ["broccoli", "cauliflower", "cabbage", "kale"]
- 如果數(shù)組長度為0掂为,則返回
undefined
;
console.log([].pop());
- 可以用
call
裕膀、apply
等被類數(shù)組對象調(diào)用,會(huì)根據(jù)類數(shù)組對象的length
屬性來決定最后一個(gè)元素的位置勇哗。如果沒有length
屬性昼扛,則默認(rèn)為0,返回undefined
欲诺。
function f() {
console.log([].pop.call(arguments)); // d
}
f('a', 's', 'd')
push
- 定義:將一個(gè)或多個(gè)元素添加到數(shù)組末尾抄谐,并返回?cái)?shù)組長度。此方法改變數(shù)組長度扰法;
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count); // 4
console.log(animals);// ["pigs", "goats", "sheep", "cows"]
- 可以結(jié)合
call()
或apply()
使用蛹含,根據(jù)length
屬性決定插入位置。沒有length
屬性則視為0塞颁。
var obj = {
length: 0,
addElem: function addElem (elem) {
// obj.length is automatically incremented
// every time an element is added.
[].push.call(this, elem);
}
};
// Let's add some empty objects just to illustrate.
obj.addElem({});
obj.addElem({});
console.log(obj.length);
// → 2
shift
- 定義: 刪除數(shù)組中的第一個(gè)元素并返回浦箱,此方法會(huì)改變原數(shù)組長度。
let arr = [,1,2];
arr.shift() // undefined;
arr.shift() // 1;
arr.shift() // 2;
arr.shift() // undefined;
- 在
while
循環(huán)中使用shift
var names = ["Andrew", "Edward", "Paul", "Chris" ,"John"];
while( (i = names.shift()) !== undefined ) {
console.log(i); // Andrew, Edward, Paul, Chris, John
}
unshift
- 定義:將一個(gè)或多個(gè)元素添加到數(shù)組開頭祠锣,并返回該數(shù)組的新長度酷窥;
- 傳入的多個(gè)參數(shù)會(huì)以塊的形式插入,順序不變伴网;
let arr = [1,2,3];
arr.unshift(4, 5) // 5
arr // [4,5,1,2,3]
splice
- 定義:從指定位置開始刪除指定個(gè)數(shù)的元素蓬推,可以在該位置增加新的元素。此方法會(huì)改變原數(shù)組澡腾,實(shí)現(xiàn)增刪改沸伏,參數(shù):
@params{start}: 起始位置索引募逞,如果超出數(shù)組長度,則從數(shù)組末尾開始馋评;如果是負(fù)數(shù)放接,則逆序,如果負(fù)數(shù)的絕對值大于數(shù)組長度留特,則從0位開始纠脾;
@params{deleteCount}:要?jiǎng)h除的元素個(gè)數(shù),包含start
位置元素蜕青,省略掉或者大于start起的元素個(gè)數(shù)苟蹈,則把start之后的全刪除。為0或者負(fù)數(shù)右核,則不刪除元素慧脱;
@item1,item2贺喝,...: 要插入的元素菱鸥,
@return 返回被修改的元素組成的數(shù)組,沒有刪除則返回空數(shù)組躏鱼。
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
var removed = myFish.splice(2, 0, 'drum', 'guitar');
// 運(yùn)算后的 myFish: ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]
// 被刪除的元素: [], 沒有元素被刪除
slice
- 定義: 淺拷貝數(shù)組的一部分作為一個(gè)新的數(shù)組返回氮采。原數(shù)組不變。參數(shù):
@params {startIndex} 索引前閉染苛,負(fù)數(shù)逆序鹊漠,默認(rèn)為0,超出數(shù)組范圍茶行,返回空數(shù)組躯概;
@params {endIndex} 索引后開,負(fù)數(shù)逆序畔师,默認(rèn)到數(shù)組末尾娶靡。
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3); // ['Orange','Lemon']