在 javascript 有分為物件與陣列。常見刪除的方法有 delete 與 splice
首先介紹一下如何辨別物件與陣列
陣列:
[javascript] var array=[ ‘a’, ‘b’, ‘c’, ‘d’ ]; console.log(a[0]); // a [/javascript]
物件:
[javascript] var object={ 0: ‘a’, 1: ‘b’, 2: ‘c’, 3: ‘d’ }; console.log(object[0]); // a [/javascript]
兩個其實很像都是 key-value ,但其實兩個繼承的 prototype 方法不同( Array 與 Object )
因此:
[javascript]
console.log(array.length); // 4
console.log(object.length); // undefined
[/javascript]
但透過 typeof 來看的話其實兩個都屬於 object,因此我們必須透過 contrustor 來判斷彼此的不同
[javascript] console.log(typeof array); // object console.log(typeof object); // object console.log(array.contrustor); console.log(array.constructor === Array); // true console.log(object.constructor === Array); // false [/javascript]
delete 與 splice
- delete 刪除物件的屬性或方法,但不會刪除物件原型的屬性或方法。 如: [javascript] Object.prototype.name=“camel_in_prototype”; var obj={ ‘name’: ‘camel }; console.log(obj.name); // camel delete obj.name; console.log(obj.name); // camel_in_prototype delete obj.name; console.log(obj.name); // camel_in_prototype  [/javascript]
- splice(index,howmany,item1,…,itemX) Array 原型的一個方法 可以選定元素後,向后刪除多個元素或插入新元素 如: [javascript] var array=[ ‘a’, ‘b’, ‘c’, ‘d’ ]; array.splice(2, 1, ‘e’); // 刪除 ‘c’,新增 ‘e’ console.log(array); // [ ‘a’, ‘b’, ‘e’ , ‘d’ ] [/javascript]
- 比較 delete 與 splice 應用在 array 上的差別 splice: [javascript] var array=[ ‘a’, ‘b’, ‘c’, ‘d’ ]; array.splice(2, 1); // 刪除 ‘c’ console.log(array.length); // 3 console.log(array); // [ ‘a’, ‘b’, ‘d’ ] [/javascript] delete: [javascript] var array=[ ‘a’, ‘b’, ‘c’, ‘d’ ]; delete array[2]; // 刪除 ‘c’ console.log(array.length); // 4 console.log(array[2]); // ‘undefined’ [/javascript]
參考資料:
http://guang.logdown.com/posts/278890-javascript-array-vs-object