1. 全部替换
2 \9 e s, q) k& a% L. K: g7 { 我们都知道 string.Replace() 函数仅能替换掉第一个匹配项。你可以通过在正则表达式的末尾添加 /g 来替换所有出现的内容。
- T% V3 T7 m9 M* i. Jvar example = "potato potato";
console.log(example.replace(/pot/, "tom"));
// "tomato potato"
console.log(example.replace(/pot/g, "tom"));
// "tomato tomato" 2. 提取唯一值
5 p0 [$ v; o' j& B) _; s 通过使用 Set 对象和 ... 运算符能够使用唯一值创建一个新数组。5 [8 f2 L9 w( v7 P; k7 `5 E
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. 将数字转换为字符串1 M; x; X( R5 c
只需要用 + 运算符带和一个空字符串即可。
( ~* O$ N) L9 H* Y7 b; ivar converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number);
// string 4.将字符串转换为数字$ x7 }: w: v; C, S$ e
只需要用 + 运算符即可。但是要注意:它仅适用于“字符串数字”。+ b# ]2 s, }' C" {( q) M
the_string = "123";
console.log(+the_string);
// 123the_string = "hello";
console.log(+the_string);
// NaN 5. 随机排列数组中的元素' t- j! }* ^9 b) d
这样最适合洗牌了:& {* d% b2 I6 @) S$ d
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.展平多维数组" q: S4 A" z3 e' D9 V! X2 W
只需使用 ... 运算符。: J! c+ a* ?( @% _
var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries);
// [1, 2, 5, 6, 7, 9] 7. 条件短路
. A2 z$ {, v. |0 ?8 b 只需要举个例子就明白了:
# y* M8 {+ @' g* pif (available) {
addToCart();
} 通过简单地使用变量和函数来简化代码:9 O/ K7 H6 d1 E
available && addToCart() 8. 动态属性名
' g! ^" f6 F# C) {6 R7 z 一直以来,我以为必须先声明一个对象,然后才能分配动态属性,但是...
: [$ I3 \4 o4 a6 S1 I% e/ T! |: Nconst dynamic = 'flavour';
var item = {
name: 'Coke',
[dynamic]: 'Cherry'
}
console.log(item);
// { name: "Coke", flavour: "Cherry" } 9. 用 length 调整货清空数组
6 R3 l1 G( M7 B! [$ p$ K7 i 如果要调整数组的大小:
; E3 T6 l% s. v2 _var 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]
|