1. 变量赋值
let a=2,b=4,c=3;let [a, b, c] = [5, 8, 12];
2. 或短路运算
let imagePath;let path = getImagePath();if(path !== null && path !== undefined && path !== '') {imagePath = path;} else {imagePath = 'default.jpg';}//Shorthandlet imagePath = getImagePath() || 'default.jpg';
3. 与短路运算
if (isLoggedin) {goToHomepage();}//ShorthandisLoggedin && goToHomepage();
4. 交换两个变量
let x = 43, y = 55;const temp = x;x = y;y = temp;//Shorthand[x, y] = [y, x];
5. 模板字符串
console.log('You got a missed call from ' + number + ' at ' + time);//Shorthandconsole.log(`You got a missed call from ${number} at ${time}`);
6. 多条件检查
if (value === 1 || value === 'one' || value === 2 || value === 'two') {// Execute some code}// Shorthand 1if ([1, 'one', 2, 'two'].indexOf(value) >= 0) {// Execute some code}// Shorthand 2if ([1, 'one', 2, 'two'].includes(value)) {// Execute some code}
7. 字符串转为数字
let total = parseInt('453');let average = parseFloat('42.6');//Shorthandlet total = +'453';let average = +'42.6';
8. 数学计算
//指数幂const power = Math.pow(4, 3); // 64// Shorthandconst power = 4**3; // 64//取整const floor = Math.floor(6.8); // 6// Shorthandconst floor = ~~6.8; // 6//找出数组中的最大和最小数字const arr = [2, 8, 15, 4];Math.max(...arr); // 15Math.min(...arr); // 2
9. 合并数组
let arr1 = [20, 30];let arr2 = arr1.concat([60, 80]);//Shorthandlet arr2 = [...arr1, 60, 80];
10. 深拷贝多级对象
为了深拷贝一个多级对象,我们要遍历每一个属性并检查当前属性是否包含一个对象。如果当前属性包含一个对象,然后要将当前属性值作为参数递归调用相同的方法(例如,嵌套的对象)。
我们可以使用JSON.stringify()和JSON.parse(),如果我们的对象不包含函数、undefined、NaN 或日期值的话。
如果有一个单级对象,例如没有嵌套的对象,那么我们也可以使用扩展符来实现深拷贝。
let obj = {x: 20, y: {z: 30}};//Longhandconst makeDeepClone = (obj) => {let newObject = {};Object.keys(obj).map(key => {if(typeof obj[key] === 'object'){newObject[key] = makeDeepClone(obj[key]);} else {newObject[key] = obj[key];}});return newObject;}const cloneObj = makeDeepClone(obj);//Shorthandconst cloneObj = JSON.parse(JSON.stringify(obj));//Shorthand for single level objectlet obj = {x: 20, y: 'hello'};const cloneObj = {...obj};
