1. 全部替换
' l7 j0 B$ H$ A5 ?$ W7 B 我们都知道 string.Replace() 函数仅能替换掉第一个匹配项。你可以通过在正则表达式的末尾添加 /g 来替换所有出现的内容。/ c. T1 z" H: e1 j) Y t A
var example = "potato potato";
console.log(example.replace(/pot/, "tom"));
// "tomato potato"
console.log(example.replace(/pot/g, "tom"));
// "tomato tomato" 2. 提取唯一值0 Y$ ?4 F7 w% F; T" i' b- L
通过使用 Set 对象和 ... 运算符能够使用唯一值创建一个新数组。8 K* q( s" F/ X$ h f
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* D% q! F' U% N2 } 只需要用 + 运算符带和一个空字符串即可。
9 H7 L, I% O9 A$ ]; X+ nvar converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number);
// string 4.将字符串转换为数字
# E& Y/ M/ A6 O6 j 只需要用 + 运算符即可。但是要注意:它仅适用于“字符串数字”。% x6 P3 M2 a4 I1 E/ j' B$ ^
the_string = "123";
console.log(+the_string);
// 123the_string = "hello";
console.log(+the_string);
// NaN 5. 随机排列数组中的元素
( a# _9 w+ W7 k! J0 }2 [4 \ X 这样最适合洗牌了:
; ^$ q: u" k0 l4 ^( Svar 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.展平多维数组+ d9 i' c. M L$ x: e
只需使用 ... 运算符。
/ @2 G7 W" O1 ^3 S% d* nvar entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries);
// [1, 2, 5, 6, 7, 9] 7. 条件短路. s7 J( g2 J, d8 J$ R
只需要举个例子就明白了:. _. L% S5 C, H/ G
if (available) {
addToCart();
} 通过简单地使用变量和函数来简化代码:
g5 Q# J4 s. ?. t3 \. G4 cavailable && addToCart() 8. 动态属性名/ b. s0 t) G, E {7 v
一直以来,我以为必须先声明一个对象,然后才能分配动态属性,但是...
* K/ V( e5 t) K* ~' S, Fconst dynamic = 'flavour';
var item = {
name: 'Coke',
[dynamic]: 'Cherry'
}
console.log(item);
// { name: "Coke", flavour: "Cherry" } 9. 用 length 调整货清空数组% L2 C2 S( t0 j1 l5 G
如果要调整数组的大小:: f! T" K; O5 F- W& V6 B
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]
|