使用 Object.prototype.toString.call() 通过 Javascript 返回对象类型 - 不适用于 IE

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4222394/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:26:54  来源:igfitidea点击:

Using Object.prototype.toString.call() to return object type with Javascript - not working in IE

javascripthtmlinternet-explorer-8

提问by dpmguise

Hopefully I can ask this in an understandable way...

希望我能以一种可以理解的方式提出这个问题......

Overall, I am trying to determine what type of object I am currently dealing with.

总的来说,我正在尝试确定我目前正在处理的对象类型。

I'm creating a collection (HTML is example, not literal) and I need to filter my collection to certain elements eg:

我正在创建一个集合(HTML 是示例,而不是文字),我需要将我的集合过滤到某些元素,例如:

        <div id="tabContentWrap">
            <div id="tab">
                <a href="http://somelink">Link Element</a><img src="img.jpg" alt="img" />
                <select id="my_select"><option value="1">1</option></select>
            </div>
        </div>

function getFilteredElements() {
    var tabContent = getElementsByClass("tabContentWrap", document.getElementById(tabWrapId), "div");

    for (var j = 0; j < tabContent.length; j++){
        tabContentLinks = tabContent[j].getElementsByTagName('*');
        for (var k = 0; k < tabContentLinks.length; k++){
            // Here i attempt to filter the collection
            if (tabContentLinks[k] == '[object HTMLSelectElement]') {
                alert("found select list");
            }
         }
     }
 }

Which works fine in Mozilla but not in Internet Explorer 8, tabContentLinks[k]returns [object]instead of [object 'ObjectType']

在 Mozilla 中工作正常但在 Internet Explorer 8 中无效,tabContentLinks[k]返回[object]而不是[object 'ObjectType']

So I investigated and discovered that you can use Object.prototype.toString.call(object)to get the object type, which again works fine in Mozilla but returns [object Object]in IE8...

所以我调查并发现你可以Object.prototype.toString.call(object)用来获取对象类型,它在 Mozilla 中再次正常工作但[object Object]在 IE8 中返回......

I call

我打电话

get_type(tabContentsLink[k]);

which runs the following function:

它运行以下功能:

function get_type(thing){
    if (thing === null) return "[object Null]";
    // special case
    return Object.prototype.toString.call(thing);
}

But this just returns [object Object]

但这只是返回 [object Object]

Does Object.prototype.toString.call()ever return the type of object in IE or am I very far off and barking up a lamppost instead of a tree?

是否Object.prototype.toString.call()曾经在 IE 中返回对象的类型,或者我离得很远并且吠叫灯柱而不是树?

回答by CMS

Well, first of all I want to tell you that Object.prototype.toStringreturns the value of the object's internal [[Class]]property, it isn't really a Type.

好吧,首先我想告诉你,Object.prototype.toString返回的是对象内部[[Class]]属性的值,它并不是真正的Type

The value of this internal property represents the specification defined classificationof an object (more info here).

此内部属性的值表示规范定义的对象分类(更多信息请点击此处)。

Javascript has only 6 language types: Object, String, Number, Boolean, Null and Undefined, that's it.

Javascript 只有 6种语言类型Object、String、Number、Boolean、Null 和 Undefined,仅此而已。

The value of the [[Class]]internal property for host objects -as DOM elements- can be anything, it is completely implementation-dependent, on built-in objects is safe to use it -except with some exceptions in IE as @Alex pointed out in the article linked in his answer-.

[[Class]]宿主对象的内部属性的值- 作为 DOM 元素 - 可以是任何东西,它完全依赖实现,在内置对象上使用它是安全的 - 除了@Alex 在文章中指出的 IE 中的一些例外链接在他的回答中-。

You are working with DOM elements, and you want to figure out what kind of node it is, my suggestion to this, is to simply use the nodeNameproperty (please avoid using tagName).

您正在使用 DOM 元素,并且想弄清楚它是什么类型的节点,我对此的建议是简单地使用nodeName属性(请避免使用tagName)

The nodeNameproperty contains the name of the node you are dealing it, in upper case, therefore you could use it as this:

nodeName属性包含您正在处理它的节点的名称(大写),因此您可以将其用作:

function getFilteredElements() {
  var tabContent = getElementsByClass("tabContentWrap", 
  document.getElementById(tabWrapId), "div");

  for (var j = 0; j < tabContent.length; j++){
    tabContentLinks = tabContent[j].getElementsByTagName('*');
    for (var k = 0; k < tabContentLinks.length; k++){
      // Here i attempt to filter the collection
      if (tabContentLinks[k].nodeName == 'SELECT') { // <- SELECT elements
        alert("found select list");
      }
    }
  }
}

回答by Alex

Rather than recreate the entire discussion and possible solutions, I'll just point you to a blog postthat discusses this exact issue.

我不会重新创建整个讨论和可能的解决方案,而是将您指向讨论这个确切问题的博客文章

回答by Chris Morgan

I don't have IE handy, but the proper way in Firefox is to use object.constructor.name(object.constructorbeing the object's constructor, .namebeing the function name).

我手头没有 IE,但在 Firefox 中正确的方法是使用object.constructor.nameobject.constructor作为对象的构造函数,.name作为函数名称)。

function Xyz() {}
new Xyz().constructor.name === 'Xyz'

But then, also,

但是,同时,

var Abc = function() {}
new Abc().constructor.name === 'Abc'

回答by harley.333

I believe IE will return simple data types, but everything else is just an object. It's a browser limitation. I don't know if IE9 is improving the situation, but that probably wouldn't help you anyway.

我相信 IE 会返回简单的数据类型,但其他一切都只是一个对象。这是浏览器限制。我不知道 IE9 是否正在改善这种情况,但这可能无论如何都无济于事。