我遇到了一个 bool 测试 variable === Object(variable)
但找不到任何描述它的东西。
它是否测试 variable
是否与 Object(variable)
相同并且是否将 Object(variable)
转换为 variable
进入对象?或者它还有别的作用吗?
如果匹配,它将循环 for (var key in variable)
并使用 key
和 variable[key]
作为另一个函数的参数.如果失败,它将按原样使用该变量。
最佳答案
它检查
- 变量已定义
- 它的值是一个对象
- 它的值不是
null
(注意:typeof null
是"object"
)
这可能是检查这 3 个条件的最简单方法,它看起来像是在循环一个非常多态的函数中的键之前运行的合理测试。
另一个是typeof variable === "object"&& variable
。
来自 the MDN :
The Object constructor creates an object wrapper for the given value. If the value is null or undefined, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.
关于JavaScript:对象(变量)是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30168679/