我正在使用myarray.length = 0
方法通過自定義Array.prototype.clear()
方法截斷數組。通過將長度設置爲0截斷數組中的數組無效
到目前爲止,據我所知,但我現在有一個特殊情況,它將length
設置爲0
,但元素仍然存在。
我運行了一個基本的數組測試,它似乎工作,但在這個更復雜的情況下,它不是,所以很難診斷問題。
這裏是我的Array.prototype
,我已經使用擴展代碼...
Object.defineProperty(Array.prototype, 'clear', {
value: function clear() {
// Clear the array using the length = 0 method. See the method's comments on links to more information and benchmarks on this technique.
this.length = 0;
},
enumerable: false,
configurable: true,
writable: false
});
當我把它在其他情況下,下面的工作出色。
var myarray = [ 1,2,3,4,5,6,6,7,8,9, new Date() ];
myarray.clear();
console.log(myarray); // all cleared. { length: 0 }
但我更復雜的情況下陣列具有約10-20元,我所說的陣列上的.clear()
,它設置長度0
但如果我console.log
像數組中的元素仍然可以看到我在上面做了。
// e.g. { 0: ..., 1: ..., 2: ..., 3: ..., 4: ..., length: 0 }
唯一的區別是,Array
對象我使用是擴展對象,具有一個覆蓋,這確實調用重寫的函數。像這樣......
function Collection() { Array.apply(this); }
Collection.prototype = Object.create(Array.prototype, {
push: {
enumerable: false,
value: function(item) {
// ...does a type checks on 'item'
Array.prototype.push.apply(this, [ item ]);
}
},
clear: {
enumerable: false,
value: function() { Array.prototype.clear.apply(this); }
}
});
這是發生在Chrome,我已加強它通到Array.prototype.clear
方法,就像我的測試一樣,但由於某種原因,它不會在第二種情況下工作。
任何想法?
好像ÿ你試圖在一個對象上使用它,而在一個對象上使用「長度」只是另一個屬性,並且不會改變對象的內容。請注意,擴展本地原型通常是一個糟糕的主意 – adeneo
我並不認爲擴展本地代碼是個不錯的主意......除了「Array」 - 與其他本地代碼相比,它具有「魔力」 –
@JaromandaX - 它是並不總是一個壞主意,但它通常是一個壞主意,這意味着我認爲應該避免它,例如在這種情況下,一個普通的「清除(Array)」可以做同樣的事情,而不用觸摸原型。至少它不是可枚舉的。 – adeneo