注意:JavaScript数组没有remove方法
splice(A,B,C);
A:开始添加或删除元素的位置
B:指定要删除的元素个数
C:参数可选
var arrayList = [1,2,3,4,5,6,7,8,9,0];
var removed = arrayList.splice(1,2);
/** removed == [1,4,5,6,7,8,9,0] */
/** 使用length属性删除末尾个别元素
var arrayList = [1,2,3,4,5,6,7,8];
arrayList.length = 3;
output: arrayList = [1,2,3,]
*/
var arrayList = [1,2,3,4,5,6];
arrayList.pop();
/** arratList==[1,2,3,4,5] */
var arrayList = [1,2,3,4,5,6];
arrayList.shift();
/** arrayList==[2,3,4,5,6] */
删除数组第一个元素,其余元素向下移动。
如果数组长度为空,或者数组长度为0,此方法返回undefined.
// 删除一个5
var arrayList = [1,2,3,4,5,6,7,8,9];
for (var i=0; i<arrayList.length; i++){
if(arrayList[i]==5){
arrayList.splice(i,1);
}
}
/** arrayList==[1,2,3,4,6,7,8,9] */
----------------------------------------------------------------
//删除两个5
var arrayList = [1,2,3,4,5,5,6,7,8,9];
for (var i=0; i<arrayList.length; i++){
if(arrayList[i]==5){
arrayList.splice(i,1);
i--;
}
}
/** arrayList==[1,2,3,4,6,7,8,9] */
var arrayList = [1,2,3,4,5,6,7,8,9];
var newArr = arrayList.filter(value,index,arr){
return value>6;
}
/** newArr==[7,8,9]; arrayList==[1,2,3,4,5,6,7,8,9] */
优点:原始数组阵型不变,返回一个包含匹配值的新数组。
var arrayList = [1,2,3,4,5,6,7,8,9];
delete arrayList[3];
console.log(arrayList);
/** arrayList==[1,2,3,empty,5,6,7,8,9] */
delete:释放元素占用的内存。
var arrayList = [1,2,3,4,5,6,7,8,9];
1: arrayList.length = 0; // 最简单
2: arrayList = [];
3: arraList.splice(0, arrayList.length); // 拼接方法
4: while(arrayList.length){ arratList.pop() } // 性能最快