【发布时间】:2014-08-12 14:15:26
【问题描述】:
来自 AngularJS isArray 来源:
return toString.call(value) === '[object Array]';
他们为什么不一起去?
return value instanceof Array;
【问题讨论】:
标签: javascript arrays angularjs
来自 AngularJS isArray 来源:
return toString.call(value) === '[object Array]';
他们为什么不一起去?
return value instanceof Array;
【问题讨论】:
标签: javascript arrays angularjs
因为如果你从不同的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 是从父窗口接收数组的参数名称):
【讨论】: