<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>判断数组的方法</title>
</head>
<body>
<script>
// 判断数组方法
var arr = [1, 2]
// console.log(typeof arr)
// 1.[] instanceof Array 返回布尔值
console.log(arr instanceof Array)
// 2.从原型入手 利用isPrototypeOf()方法,判定Array是不是在obj的原型链中,如果是,则返回true,否则false。
console.log(Array.prototype.isPrototypeOf([]));
console.log(Array.prototype.isPrototypeOf({}));
// 判断对象
// var obj = {
// test: 'test'
// }
// console.log(Object.prototype.isPrototypeOf({}));
// 3.从构造函数下手
console.log(typeof arr == 'object' && arr.constructor == Array);
// 4.跨原型链调用toString():Object.prototype.toString.call(obj)
// 每一个继承 Object 的对象都有 toString方法,如果 toString 方法没有重写的话,会返回 [Object type],其中 type 为对象的类型。但当变量类型不为对象时,使用 toString 方法会直接返回数据内容的字符串,所以我们需要使用call或者apply方法来改变toString方法的执行上下文。
// 这种方法对于所有基本的数据类型都能进行判断,即使是 null 和 undefined 。
console.log(Object.prototype.toString.call(arr)); // "[object Array]"
var test = null
var test1 = undefined
console.log(Object.prototype.toString.call(test)); // "[object Null]"
console.log(Object.prototype.toString.call(test1)); // "[object Undefined]"
console.log(Object.prototype.toString.bind(arr)());
console.log(Object.prototype.toString.apply(arr));
// 5.ES5 新增方法Array.isArray 区别instanceof不能跨框架判定数组类型
console.log(Array.isArray(arr));
</script>
</body>
</html>
判断是否为数组的方法
最新推荐文章于 2023-04-27 14:29:13 发布