js中數組刪除 splice和delete的區別,以及delete的使用


var test=[];
test[1]={name:'1',age:1};
test[2]={name:'2',age:2};
test[4]={name:'3',age:3};

console.log(test)

 

 

長度為5的關聯數組,現在開始刪除。

1.splice方法

test.splice(2,1);
console.log(test)// 打印結果如下

 

 

數組長度相應改變,但是原來的數組索引也相應改變,splice參數中第一個2,是刪除的起始索引(從0算起),在此是數組第二個元素。第二個1,是刪除元素的個數,在此只刪除一個元素,即test[2];

此時遍歷數組元素可以用普通遍歷數組的方式,比如for,因為刪除的元素在數組中並不保留。

2.delete方法

delete test[2];
console.log(test);// 打印結果如下

 

這種方式數組長度不變,此時test[2]變為undefined了,好處是原來數組的索引也保持不變,此時要遍歷數組元素可以才用.這種遍歷方式跳過其中undefined的元素,所以非常實用。

 

 

 

1.對象屬性刪除

function fun(){
this.name = 'mm';
}

var obj = new fun();
console.log(obj.name);//mm
delete obj.name;
console.log(obj.name); //undefined

2.變量刪除

var name = 'lily';
delete name;
console.log(name); //lily

直接用delete刪除不了變量
3.刪除不了原型鏈中的變量

fun.prototype.age = 18;
delete obj.age;
console.log(obj.age) //18

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM