javascript 测试变量是否是原始变量而不是对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31538010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
test if a variable is a primitive rather than an object?
提问by Chris Snow
Is it possible to test a variable to see if it is a primitive?
是否可以测试变量以查看它是否是原始变量?
I have seen lots of questions about testing an variable to see if it is an object, but not testing for a primitive.
我已经看到很多关于测试变量以查看它是否是对象的问题,但没有测试原语。
This question is academic, I don't actually need to perform this test from my own code. I'm just trying to get a deeper understanding of JavaScript.
这个问题是学术性的,我实际上不需要从我自己的代码中执行这个测试。我只是想更深入地了解 JavaScript。
回答by kieranpotts
To test for anyprimitive:
测试任何原语:
function isPrimitive(test) {
return (test !== Object(test));
};
Example:
例子:
isPrimitive(100); // true
isPrimitive(new Number(100)); // false
回答by Oriol
Object
accepts an argument and returns if it is an object, or returns an object otherwise.
Object
接受一个参数,如果它是一个对象则返回,否则返回一个对象。
Then, you can use a strict equality comparison, which compares types and values.
然后,您可以使用严格相等比较,它比较类型和值。
If value
was an object, Object(value)
will be the same object, so value === Object(value)
. If value wasn't an object, value !== Object(value)
because they will have different types.
如果value
是一个对象,Object(value)
将是同一个对象,所以value === Object(value)
. 如果 value 不是对象,value !== Object(value)
因为它们将具有不同的类型。
So you can use
所以你可以使用
Object(value) !== value