1. 全部替换
1 X- L! S7 L0 I/ `2 _* W; T 我们都知道 string.Replace() 函数仅能替换掉第一个匹配项。你可以通过在正则表达式的末尾添加 /g 来替换所有出现的内容。
* O6 z. M' e2 J7 J$ s; w& Svar example = "potato potato";
console.log(example.replace(/pot/, "tom"));
// "tomato potato"
console.log(example.replace(/pot/g, "tom"));
// "tomato tomato" 2. 提取唯一值& n7 x! c8 w) I9 M2 _
通过使用 Set 对象和 ... 运算符能够使用唯一值创建一个新数组。 _. X2 w' e( k3 J$ O
var entries = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1]
var unique_entries = [...new Set(entries)];
console.log(unique_entries);
// [1, 2, 3, 4, 5, 6, 7, 8] 3. 将数字转换为字符串$ ?) s9 w) \% p% K7 H
只需要用 + 运算符带和一个空字符串即可。% _- l8 ~( N+ `4 w
var converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number);
// string 4.将字符串转换为数字
* v; j& g: S' c1 z- x0 d+ y 只需要用 + 运算符即可。但是要注意:它仅适用于“字符串数字”。
: S% e3 q, F4 J6 G" othe_string = "123";
console.log(+the_string);
// 123the_string = "hello";
console.log(+the_string);
// NaN 5. 随机排列数组中的元素
5 t1 O# G, T: s- \/ T/ m 这样最适合洗牌了:! @3 b$ o7 D' P8 Z" A' W
var my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(my_list.sort(function() {
return Math.random() - 0.5
}));
// [4, 8, 2, 9, 1, 3, 6, 5, 7] 6.展平多维数组* _& K' r- G( |* b! O& C# ^) g8 `
只需使用 ... 运算符。1 y- k9 A% q! p! u$ E
var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries);
// [1, 2, 5, 6, 7, 9] 7. 条件短路% n, M/ A( k) N2 n2 G/ i
只需要举个例子就明白了:
/ Q* M" w. H/ |6 O' M2 Rif (available) {
addToCart();
} 通过简单地使用变量和函数来简化代码:
$ M4 D8 K) S" b. [+ ^- F8 ~# M& yavailable && addToCart() 8. 动态属性名
* i1 Z/ V7 s* ?) T) F 一直以来,我以为必须先声明一个对象,然后才能分配动态属性,但是...9 G, O7 |' q; a( c% S& g0 X
const dynamic = 'flavour';
var item = {
name: 'Coke',
[dynamic]: 'Cherry'
}
console.log(item);
// { name: "Coke", flavour: "Cherry" } 9. 用 length 调整货清空数组
0 u5 E5 |( D) w; G& h% i7 h# y* g 如果要调整数组的大小:
( O- l8 i# ]% Qvar entries = [1, 2, 3, 4, 5, 6, 7];
console.log(entries.length);
// 7
entries.length = 4;
console.log(entries.length);
// 4
console.log(entries);
// [1, 2, 3, 4]
|