Array.isArray && arr.length
通过Array.isArray来判断是否为数组,再通过length属性。
使用Array.isArray()方法和Array.length属性:可以通过Array.isArray()方法检查数组是否实际是一个数组。如果作为参数传递的对象是数组,则此方法返回true。它还检查数组是否未定义或为空。
可以使用array.length属性检查数组是否为空。此属性返回数组中的元素数。如果数字大于0,则计算结果为true。
此方法和属性可与and(&&)运算符一起使用,以确定数组是否存在且不为空。
例:
Array.isArray(emptyArray) && emptyArray.length
方法二其实和之前的方法类似,理论都是一样的。只是判断数组的方法不一样而已。
使用typeof来检测是否为数组,再通过length属性。
arr && typeof arr === "object" && arr.constructor === Array && arr.length
注:typeof判断数组和null的时候返回的是”object”。
var arr = new Array();
//输出为it is true
if(arr){
console.log("it is true");
}
//输出为it is false
if(arr == true){
console.log("it is true")
}else{
console.log("it is false");
}
Boolean(arr); //true
Number(arr); //0
Number(false); //0
Number(true); //1
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。