常用的JavaScript简写技巧

2021-10-31  本文已影响0人  small_zeo

JavaScript 的简写技巧

let x; 
let y = 8; 
// 简写
let x, y = 8;
let a, b, c; 
a = 1; 
b = 2; 
c = 3;

// 简写
let [a, b, c] = [1, 2, 3];
if(a = true){
 console.log(1);
}else{
 console.log(2);
}
// 简写
a = true ?  console.log(1) :  console.log(2);
let imagePath; 
let path = getImagePath(); 
if(path !== null && path !== undefined && path !== '') { 
  imagePath = path; 
} else { 
  imagePath = 'default.jpg'; 
} 
// 简写 
let imagePath = getImagePath() || 'default.jpg';
if (isLoggedin) {
 goToHomepage(); 
} 
// 简写
isLoggedin && goToHomepage();
let x = 'Hello', y = "javaScript"; 
const temp = x; 
x = y; 
y = temp; 
// 简写
[x, y] = [y, x];
function add(num1, num2) { 
   return num1 + num2; 
} 
// 简写
const add = (num1, num2) => num1 + num2;
console.log('You got a missed call from ' + number + ' at ' + time); 
// 简写
console.log(`You got a missed call from ${number} at ${time}`);
if (value === 1 || value === 'one' || value === 2 || value === 'two') { 
     // Execute some code 
} 
// 简写方法 1
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) { // indexOf 返回下标 没有则返回-1
    // Execute some code 
}
// 简写方法 2
if ([1, 'one', 2, 'two'].includes(value)) { // includes 返回 turn / false
    // Execute some code 
}
let firstname = 'Amitav'; 
let lastname = 'Mishra'; 
let obj = {firstname: firstname, lastname: lastname}; 
// 简写
let obj = {firstname, lastname}; // es6中的速写属性
let total = parseInt('453');  // 整型数字
let average = parseFloat('42.6');  // 浮点型数字 即 带小数点的数
// 简写
let total = +'453'; 
let average = +'42.6';
let str = ''; 
for(let i = 0; i < 5; i ++) { 
  str += 'Hello '; 
} 
console.log(str); // Hello Hello Hello Hello Hello 
// 简写 
'Hello'.repeat(5);
var arr1 = [1,2,3,4,999,1999];
Math.max(...arr); // 1999
Math.min(...arr); // 1
const power = Math.pow(4, 3); // 64 
// Shorthand 
const power = 4**3; // 64
const floor = Math.floor(6.8); // 6 
// 简写
const floor = ~~6.8; // 6

参考链接

15个常用的JavaScript简写技巧

上一篇下一篇

猜你喜欢

热点阅读