逻辑运算子(Logical Operators) 常用来判断多个条件并回传结果,有 &&
、||
以及 !
3种,介绍如下:
&&
用来验证两者是否皆为真值
用法:
运算式1 && 运算式2
若 运算式1 为假值则回传 运算式1
console.log(0 && 1); // 0
console.log(undefined && 1); // undefined
若 运算式1 为真值则回传 运算式2
console.log(1 && 0); // 0
console.log(2 && 1); // 1
验证两者其中一个是否为真值
用法:
运算式1 || 运算式2
若 运算式1 为真值则回传 运算式1
console.log(1 || 0); // 1
若 运算式1 为假值则回传 运算式2
console.log(0 || 5); // 5
console.log(undefined || 1); // 1
逻辑运算子的否定概念
用法:
!值
真值转假值,假值转真值
console.log(!1); // false
console.log(![]); // false - 物件本为真值
console.log(!0); // true
console.log(!undefined); // ture
以下为逻辑运算子的应用:
1+'1' = 11
的情况发生||
逻辑运算子来判断带入的参数,避免参数为 undefined、空值const money = 100;
function updateMoney(newMoney) {
newMoney = parseInt(newMoney) || 100;
const wellet = money + newMoney;
console.log(`钱包里有 ${wellet} 元`);
}
updateMoney(undefined);
// 钱包里有 200 元
updateMoney(100);
// 钱包里有 200 元
updateMoney(0);
// 钱包里有 200 元
但这个例子会有一个问题,就是当代入的参数为 数值0
时,原本要产出的结果应是 钱包里有 100 元
,但因为 ||
逻辑运算子 - 前面运算式为假值则回传後面运算式,所以此例中得出的最终结果会是 钱包里有 200 元
。
若修改这个错误,可以加入三元运算式来做修改
||
逻辑运算子来判定,若 newMondy 为真值或 newMondy 为 数值 0,皆会返回 true,否则返回 falseconst money = 100;
function updateMoney(newMoney) {
newMoney = parseInt(newMoney);
newMoney = (newMoney || newMoney === 0) ? newMoney : 100;
const wellet = money + newMoney;
console.log(`钱包里有 ${wellet} 元`);
}
updateMoney(undefined);
// 钱包里有 200 元
updateMoney(50);
// 钱包里有 150 元
updateMoney(0);
// 钱包里有 100 元
>>: [Day 29] Leetcode 15. 3Sum (C++)
bloc 有经验的前端工程师或多或少应该都有听过 MVC、MVP、MVVM 架构的开发方式,这些开发...
还有一种类型的切版,是EDM切版, EDM切版是什麽呢? 指的就是信里面看到的版面,像是下面这个就是...
资通安全责任等级 依照资通安全责任等级分级办法,由主管机关核定相对应之等级,按照等级决定导入系统之...
在学习JS的路上意外接触到了递回的概念,一开始觉得这是什麽鬼东西,回圈用的好端端的,为什麽需要学习难...
元件介绍 Progress bar 是能够展示当前进度的进度条元件。当一个操作需要显示目前百分比,或...