gpt4 book ai didi

javascript - 为什么 AngularJS 不在它的 isArray 函数中使用 instanceof?

转载 作者:搜寻专家 更新时间:2023-11-01 05:11:33 25 4
gpt4 key购买 nike

来自 AngularJS isArray 来源:

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

他们为什么不一起去?

return value instanceof Array;

最佳答案

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

这就是为什么他们在 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 是从父窗口接收数组的参数的名称):

Got 1, 2, 3something instanceof Array? falseObject.prototype.toString.call(something): [object Array]Array.isArray(something)? true

关于javascript - 为什么 AngularJS 不在它的 isArray 函数中使用 instanceof?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25266637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com