[英]Javascript - check if key exists - if not create it, all in one line
我正在尋找一種檢查密鑰是否存在以及是否不創建密鑰的單行方法。
var myObject = {};
//Anyway to do the following in a simpler fashion?
if (!('myKey' in myObject))
{
myObject['myKey'] = {};
}
短路評估:
!('myKey' in myObject) && (myObject.myKey = {})
myObject['myKey'] = myObject['myKey'] || {};
評論:我通常更喜歡@Nindaff和@MoustafaS提供的答案,具體取決於具體情況。
為了完整Object.assign
,您可以創建鍵/值,對任何不存在的鍵使用Object.assign
。 當您有要使用的默認選項/設置但允許用戶通過參數覆蓋時,這最有用。 它看起來像這樣:
var myObject = {};
myObject = Object.assign( { 'myKey':{} }, myObject );
這是同樣的事情,但輸出更多:
var obj = {}; console.log( 'initialized:', obj); obj = Object.assign( {'foo':'one'}, obj ); console.log( 'foo did not exist:', obj ); obj = Object.assign( {'foo':'two'}, obj ); console.log( 'foo already exists:', obj ); delete obj.foo; obj = Object.assign( {'foo':'two'}, obj ); console.log( 'foo did not exist:', obj );
注意: Object.assign在 IE 中不可用,但有一個 Polyfill
您可以使用 hasOwnProperty 或 typeof 來檢查退出或取消定義...
如果你想獲得某個鍵的值,如果不存在,返回默認值它插入該鍵的新的缺省值,那么在這里你在一行中去:
> x = {}
{}
> x['k']
undefined
> x['k'] || (x['k'] = 23) // Insert default value for non-existent key
23
> x['k']
23
> x['z'] = 5
5
> x['z'] || (x['z'] = 42) // Will not insert default value because key exists
5
顯然,您需要為可以映射到0
、 null
或undefined
鍵添加一些額外的工作
有一個指定的Proxy
內部類型適合此任務:
const myObj = new Proxy({}, {
get (target, key) {
return target.hasOwnProperty(key) && target[key] || (target[key] = {});
}
});
typeof myObj.foo === 'object' && (myObj.bar.quux = 'norf') && myObj.bar.quux === 'norf';
您可以使用Object.keys()
, Object.hasOwnProperty()
var key = {myKey:{}}, prop = Object.keys(key).pop(), myObject = {}; if (!myObject.hasOwnProperty(prop)) {myObject[prop] = key[prop]} console.log(myObject)
JavaScript ES9 (ECMAScript 2018) 引入了擴展運算符:
myObject={myKey: {}, ...myObject}
如果myKey
不存在,則將創建它,但如果存在則不會被覆蓋。 例如:
let obj = {a:1,b:2}
let test1 = {...obj,a:3} // == {a:3,b:2}
let test1 = {a:1,b:2,a:3} // == {a:3,b:2}
let test2 = {a:3,...obj} // == {a:1,b:2}
let test2 = {a:3,a:1,b:2} // == {a:1,b:2}
您可以使用邏輯空賦值 (??=)
var test = {};
(test.hello ??= {}).world ??= "Hello doesn't exist!";
如果你不知道 object 的密鑰是否存在你可以做類似的事情
object.key = (object.key || default value) operation
例子
const user = {};
user.stat = (user.stat || 0) + 1; // 1
如果你多次調用這個表達式,你會得到預期的行為
例子
const user = {};
user.stat = (user.stat || 0) + 1; // 1
user.stat = (user.stat || 0) + 1; // 2
user.stat = (user.stat || 0) + 1; // 3
使用像這樣的三元運算符實際上是一樣的
user.stat = user.stat ? user.stat + 1 : 0;
但更緊湊
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.