Skip to content

[javascript] 陣列與物件,delete與splice差異

Published: at 08:39 AM (2 min read)

在 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

參考資料:

https://github.com/dreamline2/Front_End_Exchange/wiki/%E4%BD%BF%E7%94%A8-delete-%E5%88%AA%E9%99%A4%E7%89%A9%E4%BB%B6%E7%9A%84-%22%E5%B1%AC%E6%80%A7%22-%E5%8F%8A-%22%E6%96%B9%E6%B3%95%22

http://guang.logdown.com/posts/278890-javascript-array-vs-object