Mdn reference for using hasOwnProperty with bracket notation

孤人 提交于 2021-02-11 17:00:40

问题


I am using the following code in javascript:

let group = false;
let internalId = "someString";
let appliedTo = "someOtherString";
let keyToGroupBy = true === group ? internalId : appliedTo;

if(grouped.hasOwnProperty([keyToGroupBy])) {
   ...
}

Could someone provide a reference as to why using the brackets with keyToGroupBy is working preferably in mdn? Is this considered a hack(works by chance) or it is something commonly used? is there a better way to do the same?


回答1:


The "bracket notation" is not bracket notation. What you've defined there is an array literal for an array with one element:

let group = false;
let internalId = "someString";
let appliedTo = "someOtherString";
let keyToGroupBy = true === group ? internalId : appliedTo;

console.log(Array.isArray([keyToGroupBy]))

So, it "works" because the properties of objects are either strings or symbols. Since you're not supplying a Symbol, it's going to be turned into a string. And when you do that with an array, the result is...a string equal to the first element:

let group = false;
let internalId = "someString";
let appliedTo = "someOtherString";
let keyToGroupBy = true === group ? internalId : appliedTo;

let arr = [keyToGroupBy];

console.log(String(arr) === arr[0]);
console.log(String(arr));

Turning an array to a string involves internally calling Array#join() and since there are no other values, no separator would be produced and nothing will be added to the single string that is in the array.

So, you're doing a rather roundabout way of...just checking for the string.

Is this considered a hack(works by chance)

It's mostly a hack. It's not quite abusing the rules of type conversion but certainly skirting them.

or it is something commonly used?

No, it's not. There is no reason to wrap strings into arrays...and then convert them to a string again if all you need is a string in the first place.

is there a better way to do the same?

Yes, simply don't have an array literal anywhere: grouped.hasOwnProperty(keyToGroupBy)



来源:https://stackoverflow.com/questions/60061627/mdn-reference-for-using-hasownproperty-with-bracket-notation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!