使用带有括号符号的hasOwnProperty的Mdn参考 [英] Mdn reference for using hasOwnProperty with bracket notation

查看:64
本文介绍了使用带有括号符号的hasOwnProperty的Mdn参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中使用了以下代码:

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])) {
   ...
}

有人可以提供参考,说明为什么在keyToGroupBy中使用方括号可以在mdn中更好地工作吗? 这是被认为是hack(偶然)还是它是常用的东西? 有没有更好的方法可以做到这一点?

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?

推荐答案

括号符号"不是具有一个元素的数组的数组文字:

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));

将数组转换为字符串涉及内部调用 Array#join() ,并且由于没有其他值,因此不会产生分隔符,并且不会将任何内容添加到数组中的单个字符串.

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.

因此,您正在采用一种相当round回的方式...只需检查字符串即可.

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?

是的,只是在任何地方都没有数组文字:grouped.hasOwnProperty(keyToGroupBy)

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

这篇关于使用带有括号符号的hasOwnProperty的Mdn参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆