//Longhand let marks = 26; let result; if(marks >= 30){ result = 'Pass'; }else{ result = 'Fail'; } //Shorthand let result = marks >= 30 ? 'Pass' : 'Fail';
4,默认值
如果预期值不正确的情况下,我们可以使用 OR(||) 短路运算来给一个变量赋默认值。
1 2
//Shorthand let imagePath = getImagePath() || 'default.jpg';
5,与运算
如果你只有当某个变量为 true 时调用一个函数,那么你可以使用与 (&&)短路形式书写。
1 2 3 4 5 6
//Longhand if (isLoggedin) { goToHomepage(); } //Shorthand isLoggedin && goToHomepage();
let arr = [10, 20, 30, 40]; //Longhand for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } //Shorthand //for of loop for (const val of arr) { console.log(val); } //for in loop for (const index in arr) { console.log(arr[index]); } // 我们还可以使用for...in循环来遍历对象属性。 let obj = {x: 20, y: 50}; for (const key in obj) { console.log(obj[key]); }
9,合并数组
1 2 3 4 5 6 7
let arr1 = [20, 30]; //Longhand let arr2 = arr1.concat([60, 80]); // [20, 30, 60, 80] //Shorthand let arr2 = [...arr1, 60, 80]; // [20, 30, 60, 80]