全部替换
var example = "potato potato";
console.log(example.replace(/pot/, "tom")); //替换一次
console.log(example.replace(/pot/g, "tom")); //全局替换
提取唯一值
var entries = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1]
var unique_entries = [...new Set(entries)]; // 创建一个具有唯一值的新数组
将字符串转换为数字
the_string = "123";
console.log(+the_string);// 123
the_string = "hello";
console.log(+the_string); //NAN
随机排列数组中的元素
var my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(my_list.sort(function() {
return Math.random() - 0.5
}));
展平多维数组
var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries);
缩短条件语句
if (available) {
addToCart();
} 可以替换成
available && addToCart()
动态属性名
const dynamic = 'flavour';
var item = {
name: 'Coke',
[dynamic]: 'Cherry'
}
console.log(item); // { name: "Coke", flavour: "Cherry" }
使用 length 调整/清空数组
var entries = [1, 2, 3, 4, 5, 6, 7];
entries.length = 4;
console.log(entries); // [1, 2, 3, 4]