1. 全部替换4 H3 S" \/ ?1 i% R3 O; p5 ?2 D
我们都知道 string.Replace() 函数仅能替换掉第一个匹配项。你可以通过在正则表达式的末尾添加 /g 来替换所有出现的内容。
- l8 f+ A7 f) D' L5 L5 G) `2 jvar example = "potato potato";
console.log(example.replace(/pot/, "tom"));
// "tomato potato"
console.log(example.replace(/pot/g, "tom"));
// "tomato tomato" 2. 提取唯一值
& Y6 [, m! d: s+ A 通过使用 Set 对象和 ... 运算符能够使用唯一值创建一个新数组。
" Q# g6 o8 A& z Tvar 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. 将数字转换为字符串9 L3 t4 c/ G5 m! Y t \4 z; m
只需要用 + 运算符带和一个空字符串即可。
) e% w' {5 W! H7 ~) q# e! I; lvar converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number);
// string 4.将字符串转换为数字7 [( X& o5 ~4 B. C3 [
只需要用 + 运算符即可。但是要注意:它仅适用于“字符串数字”。% N; D, O m& o% s/ C; t6 g
the_string = "123";
console.log(+the_string);
// 123the_string = "hello";
console.log(+the_string);
// NaN 5. 随机排列数组中的元素5 W$ h0 g0 i$ l% G7 }+ p) t
这样最适合洗牌了:
, m% x) M# x5 {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.展平多维数组
- E/ X% p e4 v r/ M' i7 v 只需使用 ... 运算符。
( [4 I! w# x' ]0 bvar entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries);
// [1, 2, 5, 6, 7, 9] 7. 条件短路7 [4 ]5 W4 b: ]& W" e
只需要举个例子就明白了:
: r4 B* u/ }( [if (available) {
addToCart();
} 通过简单地使用变量和函数来简化代码:6 W, ]: m% ~5 R( W
available && addToCart() 8. 动态属性名
: B% Q+ J0 H# \, r; [ W 一直以来,我以为必须先声明一个对象,然后才能分配动态属性,但是...- p, Z2 o6 g, h0 Z! t& H
const dynamic = 'flavour';
var item = {
name: 'Coke',
[dynamic]: 'Cherry'
}
console.log(item);
// { name: "Coke", flavour: "Cherry" } 9. 用 length 调整货清空数组
9 P* b- V6 |, M$ u! F7 S 如果要调整数组的大小:
8 L9 O) N6 s2 s' |: [2 wvar 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]
|