添加到数组末尾:
var arr=[1,2,3,4,5];
arr.push(6); //[1, 2, 3, 4, 5, 6]
arr[arr.length]=7; //[1, 2, 3, 4, 5, 6, 7]
arr.splice(arr.length,0,8); //[1, 2, 3, 4, 5, 6, 7,8]
console.log(arr.concat([9])); //[1, 2, 3, 4, 5, 6, 7, 8, 9] 不改变原来的数组,返回的新数组可以实现
console.log(arr.concat(10));// [1, 2, 3, 4, 5, 6, 7, 8, 10]
删除数组最后一项:
var arr=[1,2,3,4,5,6,7,8]; //[1, 2, 3, 4, 5, 6, 7, 8]
arr.pop(); //[1, 2, 3, 4, 5, 6, 7]
arr.length--; //[1, 2, 3, 4, 5, 6]
arr.length-=1; //[1, 2, 3, 4, 5]
arr.splice(arr.length-1,1); //[1, 2, 3, 4]
arr.splice(arr.length-1); //[1, 2, 3]
删除数组开头一项
var arr=[1,2,3,4,5,6,7,8]; //[1, 2, 3, 4, 5, 6, 7, 8]
arr.shift();//[2, 3, 4, 5, 6, 7, 8]
arr.splice(0,1); //[3, 4, 5, 6, 7, 8]
数组克隆
var arr=[1,2,3,4,5,6,7,8]; //[1, 2, 3, 4, 5, 6, 7, 8]
console.log(arr.splice(0)); //必须加0,原数组清空
console.log(arr.slice()); //写不写0都可以 原数组不变
console.log(arr.slice(0));
console.log(arr.concat()); //[1, 2, 3, 4, 5, 6, 7, 8]
添加到数组开头
var arr=[1,2,3,4,5,6]; //[1, 2, 3, 4, 5, 6]
arr.unshift(100); //[100, 1, 2, 3, 4, 5, 6]
arr.splice(0,0,200); //[200, 100, 1, 2, 3, 4, 5, 6]
console.log([300].concat(arr)); //[300, 200, 100, 1, 2, 3, 4, 5, 6] 原数组不变,返回的新数组是添加后的