0
点赞
收藏
分享

微信扫一扫

在JavaScript的if判断中,关于数组Array的相关思考

结论:在if判断中,无法直接使用Array转Boolean的方法判断数组是否为空数组

let array = [];
// 中间进行N步操作之后
// ...
if(array){
	console.log("数组为空数组");
}
if(array == []){
	console.log("数组为空数组");
}
if(array == 0){
	console.log("数组为空数组");
}
if(array == ""){
	console.log("数组为空数组");
}

以上判断方法是错误的。

以下是思考过程:

空数组

首先,声明一个空数组:

const array = [];

与数组的比较

众所周知,在JavaScript中,数组是引用类型,所以:

let bool;
bool = array == [];
console.log(bool); // false
bool = array === [];
console.log(bool); // false

与数字的比较

众所周知,引用类型在与基本类型进行比较时,会先将其转换成基本数据类型,然后进行比较:

bool = array == 0;
console.log(bool); // true
bool = array != 0;
console.log(bool); // false

与字符串的比较

字符串与数字同属基本数据类型,所以仍然会发生类型转换之后的比较:

bool = array == "";
console.log(bool); // true
bool = array != "";
console.log(bool); // false
// 增加一个打印,后面会对比使用
console.log(array.toString()); // ""

与Boolean的比较

Boolean与数字、字符串同属基本数据类型,所以仍然会发生类型转换之后的比较:

bool = array == true;
console.log(bool); // false
bool = array == false;
console.log(bool); // true

非空数组

在数组中push一个空字符串:

array.push("");

此时,数组与数字的比较:

bool = array == 0;
console.log(bool); // true
bool = array != 0;
console.log(bool); // false

此时,数组与字符串的比较:

bool = array == "";
console.log(bool); // true
bool = array != "";
console.log(bool); // false

此时,数组与Boolean的比较:

bool = array == true;
console.log(bool); // false
bool = array == false;
console.log(bool); // true

将数组中的值替换为0:

array.pop();
array.push(0)

此时,数组与数字的比较:

bool = array == 0;
console.log(bool); // true
bool = array != 0;
console.log(bool); // false

此时,数组与字符串的比较,就有点反直觉:

bool = array == "";
console.log(bool); // false
bool = array != "";
console.log(bool); // true

解:console.log(array.toString()); // "0"

此时,数组与Boolean的比较:

bool = array == true;
console.log(bool); // false
bool = array == false;
console.log(bool); // true

剩下还有数组中多个项,比如["", 0]这种情况,本文不再讨论。

End~~

举报

相关推荐

0 条评论