js中澳眷,給我們提供了一系列操作數(shù)組的方法。下面看例子:
shift()方法:移除數(shù)組中的第一項(xiàng)并返回該項(xiàng)
push()方法:從數(shù)組末端添加項(xiàng)
unshift()方法:在數(shù)組的前端添加項(xiàng)
pop()方法:從數(shù)組末端移除項(xiàng)
1.push使用
let colors = new Array();//創(chuàng)建一個(gè)數(shù)組
let count = colors.push("yellow", "red");//push添加兩項(xiàng)蛉艾,返回修改后數(shù)組長(zhǎng)度
console.log(count);
console.log(colors);
//2
//[ 'yellow', 'red' ]
2.pop使用
let item = colors.pop();//pop獲取最后一項(xiàng)
console.log(item);
console.log(colors);
//red
//[ 'yellow' ]
3.shift使用
let names = new Array();
names.push("HQ", "AB", "AC", "CB");
let m = names.shift();//移除數(shù)組第一項(xiàng)钳踊,并且返回
console.log(m);
console.log(names);
//HQ
//[ 'AB', 'AC', 'CB' ]
4.unshift使用
names.unshift("HQ");//數(shù)組首項(xiàng)添加一項(xiàng)
console.log(names);
//[ 'HQ', 'AB', 'AC', 'CB' ]