如果我有一個現有的POJO,並希望一些鍵/值對添加到它,我通常做它像這樣:簡單地將許多鍵/值對添加到現有JavaScript對象?
var existingObject = {
firstValue: 'hello'
};
/* some time later... */
existingObject.secondValue = 'world';
existingObject.thirdValue = 'new value';
existingObject.fourthValue = 'another value';
existingObject.fifthValue = 'another value';
existingObject.sixthValue = 'another value';
existingObject.seventhValue = 'another value';
existingObject.eighthValue = 'another value';
existingObject.adInfinitum = 'again and again...';
但我不知道是否有比這longhanded方法更有效的方法?但請注意,我正在尋找創建臨時對象的替代方法,並致電extend
。
此外,簡單地將對象存儲在一個較小的變量(如var a = existingObject;
和使用a.newValue = 'something'
)不是我正在尋找的解決方案。
有沒有辦法做到這一點?
請詳細說明。價值從何而來?哪一部分可以製作DRYer? – 2014-09-11 01:18:19
我假設你不能簡單地將它們全部添加到實例化中,就像你做了firstValue一樣?你正在具體談論實例化之後添加額外的值嗎? – kman 2014-09-11 01:20:05
你如何使用一個數組:'existingObject.values = [「hello」,「world」,「new value」,「another value」,「again and again ......」]等等。 – soktinpk 2014-09-11 01:25:35