test2 = (x > 100) ? ‘greater 100’ : (x < 50) ? ‘less 50’ : ‘between 50 and 100’;
console.log(test2); // “greater than 100”
3. 声明变量
当我们想要声明两个具有相同的值或相同类型的变量时,可以使用这种简写。
//Longhand
let test1;
let test2 = 1;
//Shorthand
let test1, test2 = 1;
4. null、undefined 和空值检查
当我们创建了新变量,有时候想要检查引用的变量是不是为非 null 或 undefined。JavaScript 确实有一个很好的快捷方式来实现这种检查。
// Longhand
if (test1 !== null || test1 !== undefined || test1 !== ‘’) {
let test2 = test1;
}
// Shorthand
let test2 = test1 || ‘’;
5. null 检查和默认赋值
let test1 = null,
test2 = test1 || ‘’;
console.log(“null check”, test2); // output will be “”
6. undefined 检查和默认赋值
let test1 = undefined,
test2 = test1 || ‘’;
console.log(“undefined check”, test2); // output will be “”
一般值检查
let test1 = ‘test’,
test2 = test1 || ‘’;
console.log(test2); // output: ‘test’
另外,对于上述的 4、5、6 点,都可以使用?? 操作符。
如果左边值为 null 或 undefined,就返回右边的值。默认情况下,它将返回左边的值。
const test= null ?? ‘default’;
console.log(test);
// expected output: “default”
const test1 = 0 ?? 2;
console.log(test1);
// expected output: 0
7. 给多个变量赋值
当我们想给多个不同的变量赋值时,这种技巧非常有用。
//Longhand
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand
let [test1, test2, test3] = [1, 2, 3];
8. 简便的赋值操作符
在编程过程中,我们要处理大量的算术运算符。这是 JavaScript 变量赋值操作符的有用技巧之一。
// Longhand
test1 = test1 + 1;
test2 = test2 - 1;<