Javascript脚本简洁之道
# Javascript脚本简洁之道
直接上代码
# ✏️ 通过条件判断给变量赋值布尔值的正确姿势
// bad
if (a === 'a') {
b = true
} else {
b = false
}
// good
b = a === 'a'
2
3
4
5
6
7
8
# ✏️ 在IF中判断数组长度不为零的正确姿势
// bad
if (arr.length !== 0) {
// todo
}
// good
if (arr.length) {
// todo
}
2
3
4
5
6
7
8
# ✏️ 同理 在IF中判断数组长度为零的正确姿势
// bad
if (arr.length === 0) {
// todo
}
// good
if (!arr.length) {
// todo
}
2
3
4
5
6
7
8
# ✏️ 简单的IF判断使用三元表达式
// bad
if (a === 'a') {
b = a
} else {
b = c
}
// good
b = a === 'a' ? a : c
2
3
4
5
6
7
8
# ✏️ 使用includes简化if判断
// bad
if (a === 1 || a === 2 || a === 3 || a === 4) {
// todo
}
// good
let arr = [1, 2, 3, 4]
if (arr.includes(a)) {
// todo
}
2
3
4
5
6
7
8
9
# ✏️ 使用some方法判断是否有满足条件的元素
// bad
let arr = [1, 3, 5, 7]
function isHasNum (n) {
for (let i = 0; i < arr.length; i ++) {
if (arr[i] === n) {
return true
}
}
return false
}
// good
let arr = [1, 3, 5, 7]
let isHasNum = n => arr.some(num => num === n)
// best
let arr = [1, 3, 5, 7]
let isHasNum = (n, arr) => arr.some(num => num === n)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# ✏️ 使用forEach方法遍历数组 不形成新数组
// bad
for (let i = 0; i < arr.length; i ++) {
// todo
arr[i].key = balabala
}
// good
arr.forEach(item => {
// todo
item.key = balabala
})
2
3
4
5
6
7
8
9
10
# ✏️ 使用filter方法过滤原数组 形成新数组
// bad
let arr = [1, 3, 5, 7],
newArr = []
for (let i = 0; i < arr.length; i ++) {
if (arr[i] > 4) {
newArr.push(arr[i])
}
}
// good
let arr = [1, 3, 5, 7]
let newArr = arr.filter(n => n > 4) // [5, 7]
2
3
4
5
6
7
8
9
10
11
# ✏️ 使用map对数组中所有元素批量处理 形成新数组
// bad
let arr = [1, 3, 5, 7],
let newArr = []
for (let i = 0; i < arr.length; i ++) {
newArr.push(arr[i] + 1)
}
// good
let arr = [1, 3, 5, 7]
let newArr = arr.map(n => n + 1) // [2, 4, 6, 8
2
3
4
5
6
7
8
9
# ✏️ 使用Object.values快速获取对象建值
let obj = {
a: 1,
b: 2
}
// bad
let values = []
for (key in obj) {
values.push(obj[key])
}
// good
let values = Object.values(obj) // [1, 2]
2
3
4
5
6
7
8
9
10
11
# ✏️ 使用Object.keys快速获取对象建名
let obj = {
a: 1,
b: 2
}
// bad
let keys = []
for (value in obj) {
keys.push(value)
}
// good
let keys = Object.keys(obj) // ['a', 'b']
2
3
4
5
6
7
8
9
10
11
# ✏️通过条件判断给变量赋值布尔值的正确姿势
// bad
let a = 1,b = 2 let temp = aa = bb = temp
// good
let a = 1,b = 2 [b, a] = [a, b]
2
3
4
# ✏️ 解构对象
// bad
setForm (person) {
this.name = person.name
this.age = person.age
}
// good
setForm ({name, age}) {
this.name = name
this.age = age
}
2
3
4
5
6
7
8
9
10
# ✏️ ||短路符设置默认值
let person = {
name: '张三',
age: 38
}
let name = person.name || '佚名'
2
3
4
5
# ✏️ &&短路符判断依赖的键是否存在防⽌报错'xxx of undfined'
let person = {
name: '张三',
age: 38,
children: {
name: '张⼩三'
}
}
let childrenName = person.children && person.childre.name
2
3
4
5
6
7
8
# ✏️ 单行IF-ELSE语句
你可能熟悉这样的常规 if -else 语句
if (10 < 100) {
console.log("True");
} else {
console.log("False");
}
你可以通过使⽤三元运算符,以更短,更简洁的⽅式编写上⾯的代码? 当然可以
10 <100 ? console.log(“True”) : console.log(“False”)
三元运算符遵循以下简单模式
condition ? trueExpression : falseExpression
2
3
4
5
6
7
8
9
10
11
# ✏️ 合并数组
你可以使⽤传播运算符( ...
)将⼀个数组的元素10扩展为另⼀个数组
const numbers = [10, 20, 30, 40];
const allNumbers = [...numbers, 50, 60, 70, 80];
console.log(allNumbers)
结果:[10, 20, 30, 40, 50, 60, 70, 80]
2
3
4
# ✏️ 从数组中删除重复项
const numbers = [1, 1, 20, 3, 3, 3, 9, 9];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers)
结果:[1,20,3,9]
2
3
4
# ✏️ 将任何内容转换为布尔值
除了true
和false
之外,JavaScript还将其他类型视为真或假
0
, ""
, null
, undefined
, NaN
,和 false
总是假
其他⼀切都为真
正因为如此,在JavaScript中,你可以将任何值转换为true和false与⼀元运算符(!)
const bool1 = !0; // true
const bool2 = !100; // false
const bool3 = !"test"; // false
const bool4 = !!"test"; // true
console.log(bool1, bool2, bool3, bool4)
结果: true false false true
2
3
4
5
6
# ✏️ 交换两个变量而不用第三个变量
let x = 1;
let y = 2;
[x, y] = [y, x];
console.log(x, y)
结果:2 1
2
3
4
5
# ✏️ 将数字转换为字符串
const num = 1 + ""
# ✏️ 将字符串转换为数字
const numStr = "123"
const num = +numStr
2
# ✏️ 将变量嵌入到字符串
通过使用反引号将字符串括起来并将变量插入之间 将变量整齐的嵌入到字符串之间 ${}
const age = 37;
const sentence = `I'm ${age} years old`;
console.log(sentence);
I'm 37 years old
2
3
4
5
# ✏️ 将字符串拆分为数组
要将字符串拆分为数组 可以使用扩展运算符(...)
const str = "Test"
const strAsArr = [...str]
console.log(strAsArr)
['T', 'e', 's', 't']
2
3
4
5
# ✏️ 可选链接
“可选的链接运算符( ?.
)允许读取位于连接对象链深处的属性的值,⽽不必明确验证链中的每个引 ⽤是否有效。” — MDN Web⽂档
假设你有⼀个 data
对象,并且想要安全地访问 data.test.value
。⾸先,你需要检查
data
是否被定义data.test
是否被定义
在 data.test.value
,你可以调⽤之前,因为,你显然⽆法读取undefined属性
const data = {test:{value:1}}
if(data && data.test){
console.log(data.test.value) // 输出:1
}
幸运的是,使⽤可选链接的⽅法,你可以简单明了地编写上⾯的代码:
const value = data?.test?.value;
console.log(value) // 输出:1
现在,你还可以安全地尝试访问不存在的属性,⽽不会出现问题
console.log(data?.this?.does?.not?.exist?.for?.sure // 输出:1
2
3
4
5
6
7
8
9
10
11
12
# ✏️ 提高JSON的可读性
我确定你以前⽤过 JSON.stringify()
。但是,你可能不使⽤它的⼀种⽅法是对JSON数据进⾏整⻬缩进
让我们看看如何完成此任务。该 JSON.stringify()
⽅法接受两个可选参数:
- 替换功能,⽤于过滤显示的JSON。在这种情况下,可以是null,因为我们不需要它
- ⼀个空格值,可以是所需空格的数⽬或字符串。在这种情况下,让我们使⽤制表符( '\t' )缩 进JSON对象以使其看起来不错
const readableJSON = JSON.stringify({ a: 'A', b: 'B' }, null, '\t');
console.log(readableJSON)
输出
{
"a": "A",
"b": "B"
}
2
3
4
5
6
7
8
# ✏️ 检查一个属性是否存在于一个对象中
你知道我们可以使⽤ in 关键字来检查 JavaScript 对象中是否存在属性吗
const person = { name: 'John Doe', salary: 1000 };
console.log('salary' in person); // returns true
console.log('age' in person); // returns false
2
3
# ✏️ 对象中的动态属性名称
使⽤动态键设置对象属性很简单。 只需使⽤ ['key_name'] 符号添加属性
const dynamic = 'flavour'
let item = {
name: 'Biscuit',
[dynamic]: 'Chocolate'
}
console.log(item) // { name: 'Biscuit', flavour: 'Chocolate' }
同样的技巧也可⽤于使⽤动态键引⽤对象属性
const keyName = 'name';
console.log(item[keyName]); // returns 'Biscuit'
2
3
4
5
6
7
8
9
10
# ✏️ 使用动态键进行对象解构
你知道可以解构⼀个变量并⽴即⽤ : 符号重命名它。 但是,当你不知道键名或键名是动态的时,你也可 以解构对象的属性吗
⾸先,让我们看看如何在解构(使⽤别名解构)时重命名变量
const person = { id: 1, name: 'John Doe' };
const { name: personName } = person;
console.log(personName); // returns 'John Doe'
让我们使⽤动态键来解构属性
const templates = { 'hello': 'Hello there', 'bye': 'Good bye'};
const templateName = 'bye';
const { [templateName]: template } = templates;
console.log(template) // returns 'Good bye'
2
3
4
5
6
7
8
9
# ✏️ 空合并 ??
运算符
当你要检查变量是 null 还是 undefined 时,此?运算符很有⽤。 当左侧为null或者undefined时,它返回 右侧值,否则返回其左侧操作数
const foo = null ?? 'Hello';console.log(foo); // returns 'Hello'
const bar = 'Not null' ?? 'Hello';
console.log(bar); // returns 'Not null'
const baz = 0 ?? 'Hello';
console.log(baz); // returns 0
2
3
4
5
在第三个示例中,返回 0 是因为即使 0 在 JavaScript 中被认为是假的,它不是 null ,也不是undefined。 你可能认为我们可以使⽤ || 运算符在这⾥,但这两者之间存在差异
const cannotBeZero = 0 || 5;console.log(cannotBeZero); // returns 5
const canBeZero = 0 ?? 5;console.log(canBeZero); // returns 0
2
# ✏️ 扁平化数组
原型 Array 上有⼀个⽅法 flat 可以让你从数组的数组中创建⼀个数组
const myArray = [{ id: 1 }, [{ id: 2 }], [{ id: 3 }]];
const flattedArray = myArray.flat(); // returns [ { id: 1 }, { id: 2 }, {id: 3 }
2
你还可以定义⼀个深度级别,指定嵌套数组结构应展平的深度。 例如:
const arr = [0, 1, 2, [[[3, 4]]]];
console.log(arr.flat(2)); // returns [0, 1, 2, [3,4]
2