2012-03-08 54 views
0

我試圖刪除一個數組的值,沒有刪除它的方法。請看下面的代碼:刪除一個變量的值而不丟失其子方法

var Project = function() { 

    //The array where all data will be stored before they are sent.. 
    this.data = []; 

    // ... Along with a function to send data to other source ... 
    this.data.send = function() { 
    } 

    //Here is where the data would be altered ... 

    //Send the data ... 
    this.data.send(); 

    //Remove the data, we don't want it when sending the next time ... 
    this.data = []; 
    // ... but this (obviously) results in the removal of the send() function ... :-(
} 

這也將刪除該功能.send(),這是不是我要找的行爲。什麼是最順暢和最合適的方式來躲避這個問題?謝謝!

+0

如果將數組的長度設置爲零,會發生什麼?在這裏黑暗中射擊。 – 2012-03-08 22:21:31

+0

你在數組中存儲函數的原因是什麼? – Eduardo 2012-03-08 22:24:35

+0

@Eduardo這是一個非常好的問題。簡單地說:我沒有正確思考。 – Zar 2012-03-09 06:27:52

回答

3

Sirko的建議應該可行,但你的問題指向設計缺陷,在我看來。

爲什麼不暴露像對象一樣的數組,其方法永遠不會改變,但它有一個內部數組,它可以隨意操縱。

var data = { 
    items: [], 
    push: function(item) { 
    this.items.push(item); 
    }, 
    send: function() { 
    // send the items 
    this.items = []; 
    } 
} 

data.push('abc'); 
data.send(); 
console.log(data.items.length) // 0 

讓數組成爲數組,並使用其他構造來操作它們。

+0

準確地說,我一直在尋找,不知道爲什麼我從一開始就不這樣做,謝謝! – Zar 2012-03-09 06:29:06

+0

目前還不清楚爲什麼數組需要被包裝在另一個對象中,而重新實現一堆數組方法。爲什麼?整個JS的靈活性意味着你不必去除'.push()'和'.length()'和所有訪問器。您可以將新方法添加到任何現有對象,並保留其已有的所有方法。如果你想要一個'.clear()'方法,它保留現有的屬性,但清除數組,你可以添加一個'.clear()'方法。 – jfriend00 2012-03-09 12:33:59

+0

我可以考慮將數組封裝到另一個對象中的唯一正當理由是,如果您確實想要從其他代碼隱藏數組方法,但看起來並不是這種情況。 – jfriend00 2012-03-09 12:34:29

2

隨着this.data = [];你用一個新的數組替換舊的數組對象,從而失去所有連接的功能。您必須修改現有對象才能保留屬性。例如,你可以使用splice[email protected]):

this.data.splice(0, this.data.length); 

或者如艾略特博納維爾建議你可以設置長度爲零([email protected]

this.data.length = 0; 
+0

啊,真好!我正在討論一些可怕的解決方案,包括遍歷所有屬性。 – Corbin 2012-03-08 22:23:47

+0

與濫用數組的可怕解決辦法相反? ; P – JonnyReeves 2012-03-08 22:32:59

+0

好吧。當我看到這個問題時,我的第一反應是健康的「wtf?」但它的陰謀淹沒了我的大腦告訴我問扎爾爲什麼他正在這樣做:)。 – Corbin 2012-03-08 22:38:26

1

你可以這樣做:

this.data.length = 0; 

然後,您的現有數組將保留爲空,同時保留所有其他屬性。這裏是關於使用javascript數組的an interesting reference