2015-07-12 50 views
0

我需要給某些「數組」添加一些值,但我想,如果這個數組已經有我想要插入的值來獲得一些異常,哪個對象或「特殊數組」我可以在節點中使用java腳本JS陣列與節點中的鍵

+2

你有一些代碼與我們分享? – Stefan

+0

是否有一個原因,你不能只使用一個幫助函數,運行'indexOf'檢查並手動拋出錯誤? – SmokeyPHP

回答

1

我想你想是這樣的:

var dataStore = { 
 
    _dataStore: {}, 
 
    add: function(key, data) { 
 
    if (this._dataStore[key]) { 
 
     throw new Error('already exist'); 
 
    } 
 
    this._dataStore[key] = data; 
 
    }, 
 
    get: function(key) { 
 
    return this._dataStore[key]; 
 
    } 
 
}; 
 
//usage 
 
dataStore.add('some-key', 'test'); 
 
//will throw exception 
 
//dataStore.add('some-key', 'test'); 
 

 
alert(dataStore.get('some-key'));

0

最好是使用對象。用於這種東西的好庫也是lodash