来自AngularJS isArray
来源:
return toString.call(value) === '[object Array]';
为什么不跟他们一起去?
return value instanceof Array;
答案 0 :(得分:8)
因为如果你收到来自不同window
的数组(例如,另一个框架或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, 3 something instanceof Array? false Object.prototype.toString.call(something): [object Array] Array.isArray(something)? true