简体   繁体   English

如何检测在JavaScript中使用in运算符是否安全?

[英]How can I detect whether it is safe to use `in` operator in Javascript?

This statement 这个说法

 if ('foo' in bar)

throws a TypeError if bar is a string. 如果bar是字符串,则抛出TypeError。 I presume it's possible to have the same error for other types of object. 我认为其他类型的对象可能会出现相同的错误。

How can I tell if bar is an object which supports the in operator? 如何判断bar是否是支持in运算符的对象?

This code isn't sufficient: if foo is a string, it passes through to the in statement and throws. 这段代码是不够的:如果foo是一个字符串,它将传递给in语句并抛出。

if (foo instanceof Object && ! (foo instanceof String))
{
    if ('foo' in foo) {}
}

The in operator throws a TypeError is the right operand is not an object. in运算符将引发TypeError是正确的操作数不是对象。

You can check if a value is an object using 您可以使用以下方法检查值是否为对象

Object(value) === value;

Additionally, in operator calls internal [[HasProperty]] method. 另外, in操作员中调用内部的[[HasProperty]]方法。 For ordinary objects it should never throw , but it might be the case in some exotic objects. 对于普通对象,永远不要抛出 ,但是在某些奇异对象中可能就是这种情况。 For example, 例如,

var proxy = new Proxy({}, {has: () => {throw "Can't use `in`"}});
"property" in proxy; // Error: Can't use `in`

To handle these cases, I think you can only use a try statement, as ringø suggested . 为了处理这些情况,我认为您只能使用try语句,如ringø建议

var o = {};

console.log(o.constructor === Object && o !== null); //true

To catch any error 捕捉任何错误

try { 
   if ('foo' in bar) { 
   }
}
catch(e) {
   // 'foo' is not in bar
}

or if you want just to catch errors for 'foo' in bar 或者,如果您只想捕获 'foo' in bar错误

var inbar = false;
try { if ('foo' in bar) inbar = true; } 
catch(e) {}

if (inbar) {
   ...
}

How can I detect whether it is safe to use in operator in Javascript? 如何检测Javascript in运算符是否安全?

From the ES5 spec 从ES5规范

The production RelationalExpression : RelationalExpression in ShiftExpression is evaluated as follows: ShiftExpression中的生产RelationalExpression:RelationalExpression的评估如下:

  1. Let lref be the result of evaluating RelationalExpression. 令lref为评估RelationalExpression的结果。
  2. Let lval be GetValue(lref). 令lval为GetValue(lref)。
  3. Let rref be the result of evaluating ShiftExpression. 令rref为评估ShiftExpression的结果。
  4. Let rval be GetValue(rref). 令rval为GetValue(rref)。
  5. If Type(rval) is not Object, throw a TypeError exception. 如果Type(rval)不是Object,则抛出TypeError异常。
  6. Return the result of calling the [[HasProperty]] internal method of rval with argument ToString(lval). 返回使用参数ToString(lval)调用rval的[[HasProperty]]内部方法的结果。

Emphasis mine. 强调我的。

In ES5 Type() can be 在ES5中, Type()可以是

  • Undefined 未定义
  • Null 空值
  • Boolean 布尔型
  • String
  • Number
  • Object 宾语

So to prevent TypeError s from happening, you have to make sure that it's not 因此,为防止TypeError发生,您必须确保它不会

  • undefined
  • null
  • true or false true还是false
  • any string value 任何字符串值
  • any number value 任何数值

EcmaScript 2015 introduces the Symbol type as well. EcmaScript 2015也引入了Symbol类型。

An example function might look like: 一个示例函数可能类似于:

function canCallIn(arg) {
    if (arg === null ||
        arg === undefined)
        return false;
    switch (typeof arg) {
        case 'boolean':
        case 'string':
        case 'symbol':
        case 'number':
            return false;
    }
    return true;
}

Although you may be able to make various optimizations. 尽管您可以进行各种优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以使用Javascript检测复选框是否被选中吗? - Can I use Javascript to detect whether a checkbox has been checked? 如何使用原型检测是否禁用了JavaScript? - How can I detect whether JavaScript is disabled using prototype? 我如何检测正在使用的浏览器是否是最新的 - How can i detect whether browser in use is the latest one 我可以使用 Javascript 来检测用户是否在另一个打开的选项卡上,而不是我的网站上吗? - Can I use Javascript do detect whether a user is on another open tab, rather than my website? 如何检测 iframe 是否已加载? - How can I detect whether an iframe is loaded? 使用Javascript,如何检测浏览器是否在平板电脑设备上与手机上运行? - Using Javascript, how can I detect whether the browser is running on a tablet device vs a phone? 如何检测浏览器是否可移动,并使用javascript“ if else”以不同大小显示视频? - How can I detect whether or not a browser is mobile and display a video at different sizes with javascript “if else”? 如何使用javascript检测网页是否在移动设备上响应 - how to use javascript to detect whether a web page is responsive on mobile 如何使用 jquery 检测对话框是否已打开? - How can I use jquery to detect whether a dialog has been opened? 如何使用 JavaScript 检测我是否在缓存页面上 - How can I use JavaScript to detect if I am on a cached page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM