Ben*_*Ben 4 javascript arrays angularjs
来自AngularJS isArray来源:
return toString.call(value) === '[object Array]';
Run Code Online (Sandbox Code Playgroud)
为什么不跟他们一起去?
return value instanceof Array;
Run Code Online (Sandbox Code Playgroud)
因为如果你从不同的接收阵列window(例如,另一帧或iframe,一个子窗口,父窗口,等等),它不会instanceof对Array在构造函数中的窗口.
这就是为什么在ES5中他们将Array.isArray功能添加到JavaScript中,所以我们可以停止这样做,这看起来像这样:
if (Object.prototype.toString.call(theArray) === "[object Array]") ...
Run Code Online (Sandbox Code Playgroud)
此示例的各个方面: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>
Run Code Online (Sandbox Code Playgroud)
子窗口:
<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>
Run Code Online (Sandbox Code Playgroud)
输出(在子窗口中)(something是从父项接收数组的参数的名称):
Got 1, 2, 3 something instanceof Array? false Object.prototype.toString.call(something): [object Array] Array.isArray(something)? true
| 归档时间: |
|
| 查看次数: |
592 次 |
| 最近记录: |