声明多个变量
js
// 常规写法
let x
let y = 20
// 简写
let x,
y = 20// 常规写法
let x
let y = 20
// 简写
let x,
y = 20多个变量赋值
可以使用数组解构来为多个变量赋值
js
// 常规写法
let a, b, c
a = 5
b = 8
c = 12
// 简写
let [a, b, c] = [5, 8, 12]// 常规写法
let a, b, c
a = 5
b = 8
c = 12
// 简写
let [a, b, c] = [5, 8, 12]自增自减
js
var a = 1;
// 使a自增1
a++;
console.log("a = " +a);var a = 1;
// 使a自增1
a++;
console.log("a = " +a);后++(a++)
前++(++a)
相同:无论是a++,还是++a,都会立即使原变量的值自增1。
不同:①a++的值等于原变量的值(自增前的值)。 ++a的值等于原变量自增后的新值。
js
var a = 1;
console.log(a++);
console.log("a = " +a);
var a = 1;
console.log(++a);
console.log("a = " +a);var a = 1;
console.log(a++);
console.log("a = " +a);
var a = 1;
console.log(++a);
console.log("a = " +a);短路语法
使用 || 短路语法来设置默认值,防止抛异常
js
// 常规写法
let imagePath
let path = getImagePath()
if (path !== null && path !== undefined && path !== '') {
imagePath = path
} else {
imagePath = 'default.jpg'
}
// 简写
let imagePath = getImagePath() || 'default.jpg'// 常规写法
let imagePath
let path = getImagePath()
if (path !== null && path !== undefined && path !== '') {
imagePath = path
} else {
imagePath = 'default.jpg'
}
// 简写
let imagePath = getImagePath() || 'default.jpg'交换两个变量的值
交换两个变量值的时候我们一般会引入第三个临时变量,但是现在我们可以用数组的解构去实现
js
let x = 'Hello',
y = 55
// 常规写法
const temp = x
x = y
y = temp
// 简写
const [x, y] = [y, x]let x = 'Hello',
y = 55
// 常规写法
const temp = x
x = y
y = temp
// 简写
const [x, y] = [y, x]ES6模板字符串
js
// 常规写法
console.log('You got a missed call from ' + number + ' at ' + time)
// 简写
console.log(`You got a missed call from ${number} at ${time}`)// 常规写法
console.log('You got a missed call from ' + number + ' at ' + time)
// 简写
console.log(`You got a missed call from ${number} at ${time}`)多个条件判断
js
// 常规写法
if (value === 1 || value === 'one' || value === 2 || value === 'two') {
// 其他代码...
}
// 简写 1
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) {
// 其他代码...
}
// 简写 2
if ([1, 'one', 2, 'two'].includes(value)) {
// 其他代码...
}// 常规写法
if (value === 1 || value === 'one' || value === 2 || value === 'two') {
// 其他代码...
}
// 简写 1
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) {
// 其他代码...
}
// 简写 2
if ([1, 'one', 2, 'two'].includes(value)) {
// 其他代码...
}
liang14658fox