【问题标题】:Why does AngularJS not use instanceof in its isArray function?为什么 AngularJS 不在其 isArray 函数中使用 instanceof?
【发布时间】:2014-08-12 14:15:26
【问题描述】:

来自 AngularJS isArray 来源:

return toString.call(value) === '[object Array]';

他们为什么不一起去?

return value instanceof Array;

【问题讨论】:

    标签: javascript arrays angularjs


    【解决方案1】:

    因为如果你从不同的window 收到一个数组(例如,另一个框架或 iframe、一个子窗口、一个父窗口等),它不会是 instanceof 中的 Array 构造函数em>你的窗口。

    这就是为什么在 ES5 中他们将 Array.isArray function 添加到 JavaScript 中,所以我们可以停止这样做,看起来像这样:

    if (Object.prototype.toString.call(theArray) === "[object Array]") ...
    

    各个方面的示例:Live Copy

    父窗口:

    <body>
      <input type="button" value="Click To Open Window">
    <script>
      (function() {
        "use strict";
    
        var wnd;
    
        document.querySelector("input").onclick = function() {
          wnd = window.open("http://jsbin.com/yimug/1");
          display("Opened, waiting for child window to load...");
          setTimeout(waitForChild, 10);
        };
    
        function waitForChild() {
          if (wnd && wnd.sendMeSomething) {
            display("Child window loaded, sending [1, 2, 3]");
            wnd.sendMeSomething([1, 2, 3]);
          }
        }
    
        function display(msg) {
          var p = document.createElement('p');
          p.innerHTML = String(msg);
          document.body.appendChild(p);
        }
      })();
    </script>
    </body>
    

    子窗口:

    <script>
      (function() {
        "use strict";
    
        window.sendMeSomething = function(something) {
          display("Got " + something.join(", "));
          display("something instanceof Array? " + (something instanceof Array));
          display("Object.prototype.toString.call(something): " + Object.prototype.toString.call(something));
          if (Array.isArray) {
            display("Array.isArray(something)? " + Array.isArray(something));
          }
        };
        function display(msg) {
          var p = document.createElement('p');
          p.innerHTML = String(msg);
          document.body.appendChild(p);
        }
      })();
    </script>
    

    输出(在子窗口中)something 是从父窗口接收数组的参数名称)

    得到 1, 2, 3 一些instanceof数组?错误的 Object.prototype.toString.call(something): [对象数组] Array.isArray(什么)?真的

    【讨论】:

    • 你是怎么知道的?有没有一本书讨论这些“细节”。
    • @Ben:LOL 很好的问题。多年来一直在讨论 JavaScript,讨论组,自己遇到类似的问题,阅读和回答关于 SO 的问题,并深入研究 JavaScript 的深层内部工作原理......我还没有找到一本涵盖这些怪事的书 特别是,但一本体面的深入书籍应该涵盖其中的许多内容。
    • @T.J.Crowder 感谢您的回答。
    • @Ben:很高兴,希望对您有所帮助。 :-)
    猜你喜欢
    • 2010-09-18
    • 1970-01-01
    • 2016-10-10
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-05
    • 2012-12-23
    • 1970-01-01
    相关资源
    最近更新 更多