鉴于一些对象y,我怎样才能找出最具体X的表达方式
y instanceof X
Run Code Online (Sandbox Code Playgroud)
评估到true?
例如,以下两个表达式都评估为true
[] instanceof Object
[] instanceof Array
Run Code Online (Sandbox Code Playgroud)
......但Array更具体Object.
这是控制台的一些输出,说明了我的问题
var a=document.createElement("select"); <ENTER>
undefined
a.appendChild(document.createElement("option")); <ENTER>
<option>?</option>?
a
<select>?…?</select>?
a.options
[<option>?</option>?]
a.options[0];
<option>?</option>?
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好。但现在
我输入a.options. 并且我要输入 forEach 但我注意到 forEach 没有被列出。
a.options.forEach(function() {});
VM1048:2 Uncaught TypeError: a.options.forEach is not a function
at <anonymous>:2:11
at Object.InjectedScript._evaluateOn (<anonymous>:905:140)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:838:34)
at Object.InjectedScript.evaluate (<anonymous>:694:21)
Run Code Online (Sandbox Code Playgroud)
然而 a.options 看起来像一个数组
而 forEach 绝对适用于数组,没有错误。
a=[1,2];
[1, 2]
typeof a
"object"
a.forEach(function(){});
undefined
Run Code Online (Sandbox Code Playgroud)
我猜选择框的选项可能不是数组..那么它们是什么?
我听说过 'arguments' 伪数组.. 我想也许选择框的 'options' 是这样的?/ 一些与数组具有相似语法的对象?
为了澄清我的标题,我需要一种方法来确定一个对象不是String,Number,Boolean或任何其他预定义的JavaScript对象.想到的一种方法是:
if(!typeof myCustomObj == "string" && !typeof myCustomObj == "number" && !typeof myCustomObj == "boolean") {
Run Code Online (Sandbox Code Playgroud)
我可以查看是否myCustomObj是一个对象,如下所示:
if(typeof myCustomObj == "object") {
Run Code Online (Sandbox Code Playgroud)
这只适用于原始值,因为这typeof new String("hello world") == "object")是真的.
确定对象是否不是预定义JavaScript对象的可靠方法是什么?