1. 全部替换7 P: |8 W% h+ Z
我们都知道 string.Replace() 函数仅能替换掉第一个匹配项。你可以通过在正则表达式的末尾添加 /g 来替换所有出现的内容。. Q. n. j; e2 b7 L8 }; P
var example = "potato potato";
console.log(example.replace(/pot/, "tom"));
// "tomato potato"
console.log(example.replace(/pot/g, "tom"));
// "tomato tomato" 2. 提取唯一值
; y$ k( W0 J- J 通过使用 Set 对象和 ... 运算符能够使用唯一值创建一个新数组。% ]. I: W& `+ T9 Z& D
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. 将数字转换为字符串3 w2 m5 v$ M' G. i- x4 S
只需要用 + 运算符带和一个空字符串即可。
6 E6 b$ a! D* vvar converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number);
// string 4.将字符串转换为数字2 U- _; d1 s/ ^ R
只需要用 + 运算符即可。但是要注意:它仅适用于“字符串数字”。! K$ M! b# a) U5 \! D
the_string = "123";
console.log(+the_string);
// 123the_string = "hello";
console.log(+the_string);
// NaN 5. 随机排列数组中的元素. e- M% u/ }- Q, V" h$ L
这样最适合洗牌了:
/ j+ p0 c% `& p F0 dvar 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.展平多维数组
: ?4 B% }5 i) o2 w5 b, A r, Y 只需使用 ... 运算符。
8 w8 z: `9 c! v- \var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries);
// [1, 2, 5, 6, 7, 9] 7. 条件短路- u( K& A! P( ]5 ~
只需要举个例子就明白了:
; f3 l; y; B' i+ Q) Z4 n3 W% lif (available) {
addToCart();
} 通过简单地使用变量和函数来简化代码:
' v) [4 f0 Y2 A" Bavailable && addToCart() 8. 动态属性名" X2 V- {- o8 d% q: A6 ?* b) A. X( m
一直以来,我以为必须先声明一个对象,然后才能分配动态属性,但是...$ ]& X9 T6 @0 ?* `! E! K
const dynamic = 'flavour';
var item = {
name: 'Coke',
[dynamic]: 'Cherry'
}
console.log(item);
// { name: "Coke", flavour: "Cherry" } 9. 用 length 调整货清空数组1 K2 _0 f3 y2 W1 l) p
如果要调整数组的大小:5 c0 W! V8 i$ a# I0 R7 i
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]
|