1. 全部替换
( L* D9 b0 [5 k/ F+ q 我们都知道 string.Replace() 函数仅能替换掉第一个匹配项。你可以通过在正则表达式的末尾添加 /g 来替换所有出现的内容。) N( l# P+ ^$ t8 O4 s2 e, B
var example = "potato potato";
console.log(example.replace(/pot/, "tom"));
// "tomato potato"
console.log(example.replace(/pot/g, "tom"));
// "tomato tomato" 2. 提取唯一值/ u& Z8 h) R7 H# m4 s) P; B
通过使用 Set 对象和 ... 运算符能够使用唯一值创建一个新数组。& x, I6 Y3 m8 N* r$ {! y5 o9 C
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. 将数字转换为字符串
n- V: }4 G) N3 P 只需要用 + 运算符带和一个空字符串即可。
D. f% n0 |$ R0 [var converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number);
// string 4.将字符串转换为数字
0 Q9 a- l. S" G3 h: q* G4 r 只需要用 + 运算符即可。但是要注意:它仅适用于“字符串数字”。! f9 o2 {7 y. r0 c8 {8 f+ ^/ r; ~' b
the_string = "123";
console.log(+the_string);
// 123the_string = "hello";
console.log(+the_string);
// NaN 5. 随机排列数组中的元素, l6 H4 D- [" ^: F3 _6 S2 g5 |
这样最适合洗牌了:
! O9 V4 P4 q1 ]2 k. }# L* X$ n; hvar 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.展平多维数组- }0 G, R7 `. c0 \# I2 ?# h
只需使用 ... 运算符。
( m! j% q2 g$ k* Q- i; C/ b4 g Lvar entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries);
// [1, 2, 5, 6, 7, 9] 7. 条件短路
E% ~+ |) v3 u7 v8 |7 K( ? 只需要举个例子就明白了:5 U; m' |' i$ F, Y( ?8 H
if (available) {
addToCart();
} 通过简单地使用变量和函数来简化代码:' G+ a9 s" f8 Y4 O$ a: ^
available && addToCart() 8. 动态属性名0 X9 R& L' w0 H2 {' z
一直以来,我以为必须先声明一个对象,然后才能分配动态属性,但是...+ ^- U# ]8 S+ u3 e! y2 U( ?7 _
const dynamic = 'flavour';
var item = {
name: 'Coke',
[dynamic]: 'Cherry'
}
console.log(item);
// { name: "Coke", flavour: "Cherry" } 9. 用 length 调整货清空数组) ?5 u& L: O) U, }1 h: K: E; Z/ `& g# L# U
如果要调整数组的大小:
I3 }4 @8 q* p! i, j+ i; J8 cvar 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]
|