判断一个变量是否为数组最推荐的方法是使用 array.isarray(),因为它准确、可靠且能正确处理跨iframe等不同执行环境下的数组判断;2. typeof 不能用于判断数组,因为它对所有对象(包括数组、普通对象、null)都返回"object",无法区分具体类型;3. instanceof array 在跨执行环境(如多个iframe)时会失效,因为不同环境中的 array 构造函数不相等,导致判断错误;4. object.prototype.tostring.call() 也能正确判断数组且跨环境安全,但语法较冗长,适合需要通用类型判断的场景,而 array.isarray() 更简洁高效,是判断数组的首选方法。

在JavaScript里,要判断一个变量是不是数组,最直接、最推荐的方法就是使用
Array.isArray()

判断一个变量
myVar
if (Array.isArray(myVar)) {
console.log("这是一个数组!");
} else {
console.log("这不是一个数组。");
}Array.isArray()
true
false

说实话,刚接触JavaScript的时候,很多人(包括我自己在内)都会下意识地想用
typeof
typeof
typeof
"object"
null
"object"
"object"
console.log(typeof []); // "object"
console.log(typeof {}); // "object"
console.log(typeof null); // "object"
console.log(typeof "hello"); // "string"
console.log(typeof 123); // "number"你看,它根本无法区分数组和普通对象,甚至连
null
typeof

instanceof
myVar instanceof Array
let arr = [1, 2, 3];
console.log(arr instanceof Array); // true
let obj = {};
console.log(obj instanceof Array); // false但是,
instanceof
iframe
vm
iframe
Array
Array
Array
<!-- index.html -->
<iframe id="myFrame" src="about:blank"></iframe>
<script>
const iframe = document.getElementById('myFrame');
const iframeDoc = iframe.contentWindow.document;
const iframeArray = iframe.contentWindow.Array; // 获取iframe中的Array构造函数
const arrInMain = [];
const arrInIframe = iframeDoc.createElement('script').parentNode; // 随便找个iframe中的数组
console.log(arrInMain instanceof Array); // true (主窗口的数组是主窗口Array的实例)
console.log(arrInIframe instanceof Array); // false (iframe的数组不是主窗口Array的实例)
console.log(arrInIframe instanceof iframeArray); // true (iframe的数组是iframe中Array的实例)
</script>在这种跨上下文的情况下,
instanceof Array
instanceof
Object.prototype.toString.call()
"[object Array]"
let arr = [1, 2, 3];
let obj = {};
let str = "hello";
let num = 123;
let nul = null;
let und = undefined;
console.log(Object.prototype.toString.call(arr)); // "[object Array]"
console.log(Object.prototype.toString.call(obj)); // "[object Object]"
console.log(Object.prototype.toString.call(str)); // "[object String]"
console.log(Object.prototype.toString.call(num)); // "[object Number]"
console.log(Object.prototype.toString.call(nul)); // "[object Null]"
console.log(Object.prototype.toString.call(und)); // "[object Undefined]"这种方法之所以可靠,是因为
Object.prototype.toString
[[Class]]
[[Class]]
Object.prototype.toString.call()
Array.isArray()
异同点:
Array.isArray()
Object.prototype.toString.call()
Object.prototype.toString.call()
Date
RegExp
Function
Array.isArray()
Array.isArray()
Object.prototype.toString.call()
所以,我的建议是,如果你只是想判断一个变量是不是数组,那就无脑用
Array.isArray()
Date
RegExp
Object.prototype.toString.call()
Array.isArray()
以上就是js怎么判断一个变量是否是数组的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号