1、申明变量
let x; let y = 20; // 简写let x, y = 20;
2、多个变量赋值
咱们能够应用数组解构来在一行中给多个变量赋值
let a, b, c; a = 5; b = 8; c = 12;// 简写let [a, b, c] = [5, 8, 12];
3、三元运算符
if(a = true){ console.log(1);}else{ console.log(2);}// 简写a = true ? console.log(1) : console.log(2);
4、赋默认值
咱们能够应用 || 运算符来给一个变量赋默认值
let imagePath; let path = getImagePath(); if(path !== null && path !== undefined && path !== '') { imagePath = path; } else { imagePath = 'default.jpg'; } // 简写 let imagePath = getImagePath() || 'default.jpg';
5、与运算符(&&)
如果你只有当某个变量为 true 时调用一个函数,那么你能够应用与 (&&)运算符模式书写
if (isLoggedin) { goToHomepage(); } // 简写isLoggedin && goToHomepage();
6、替换两个变量
为了替换两个变量,咱们通常应用第三个变量。然而咱们也能够应用数组解构赋值来替换两个变量。
let x = 'Hello', y = "javaScript"; const temp = x; x = y; y = temp; // 简写[x, y] = [y, x];
7、箭头函数
function add(num1, num2) { return num1 + num2; } // 简写const add = (num1, num2) => num1 + num2;
8、模板字符串
咱们个别应用 + 运算符来连贯字符串变量。应用 ES6 的模板字符串,咱们能够用一种更简略的办法实现这一点。
console.log('You got a missed call from ' + number + ' at ' + time); // 简写console.log(`You got a missed call from ${number} at ${time}`);
9、多条件查看
对于多个值匹配,咱们能够将所有的值放到数组中,而后应用indexOf()或includes()办法。
if (value === 1 || value === 'one' || value === 2 || value === 'two') { // Execute some code } // 简写办法 1if ([1, 'one', 2, 'two'].indexOf(value) >= 0) { // indexOf 返回下标 没有则返回-1 // Execute some code }// 简写办法 2if ([1, 'one', 2, 'two'].includes(value)) { // includes 返回 turn / false // Execute some code }
10、对象属性赋值
如果变量名和对象的属性名雷同,那么咱们只须要在对象语句中申明变量名,而不是同时申明键和值。JavaScript 会主动将键作为变量的名,将值作为变量的值。
let firstname = 'Amitav'; let lastname = 'Mishra'; let obj = {firstname: firstname, lastname: lastname}; // 简写let obj = {firstname, lastname}; // es6中的速写属性
11、字符串转换成数字
除了应用内置属性parseInt和parseFloat能够用来将字符串转为数字。咱们还能够简略地在字符串前提供一个一元运算符 (+) 来实现这一点。
let total = parseInt('453'); // 整型数字let average = parseFloat('42.6'); // 浮点型数字 即 带小数点的数// 简写let total = +'453'; let average = +'42.6';
12、反复一个字符串屡次
为了反复一个字符串 N 次,你能够应用for循环。然而应用repeat()办法,咱们能够一行代码就搞定。
let str = ''; for(let i = 0; i < 5; i ++) { str += 'Hello '; } console.log(str); // Hello Hello Hello Hello Hello // 简写 'Hello'.repeat(5);
13、优雅的获取数组中的最大值 同理也能够求得最小值
咱们能够应用 for 循环来遍历数组中的每一个值,而后找出最大或最小值。咱们还能够应用 Array.reduce() 办法来找出数组中的最大和最小数字。然而应用扩大符号,咱们一行就能够实现。
var arr1 = [1,2,3,4,999,1999];Math.max(...arr); // 1999Math.min(...arr); // 1
14、指数幂
咱们能够应用Math.pow()办法来失去一个数字的幂。有一种更短的语法来实现,即双星号( ** )
const power = Math.pow(4, 3); // 64 // Shorthand const power = 4**3; // 64
15、双非位运算符 (~~)
双非位运算符是Math.floor()办法的缩写。
const floor = Math.floor(6.8); // 6 // 简写const floor = ~~6.8; // 6