简体   繁体   中英

what is the best way define array cell if it's not defined?

I have a 2nd level array, that at a cetain point in the code can be ether undefined or contain value. If it is undefined I need to define it, without giving it any value. this is what i did:

arr[arr2["stripID"]] = typeof(arr[arr2["stripID"]]) === 'undefined' ? [] : arr[arr2["stripID"]];

is there a better or shorter way?

arr[arr2["stripID"]] = arr[arr2["stripID"]] || [];

Should do what you want.

The || operator returns the first truthy value in the expression. Because an array is truthy, and the only other value it can be is undefined (falsy), this'll work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM