几个常用JS小方法

54 阅读1分钟

下面给出了几个常用的 JavaScript 小技巧

1. 全部替换

我们都知道 string.Replace() 函数仅能替换掉第一个匹配项。

你可以通过在正则表达式的末尾添加 /g 来替换所有出现的内容。

var  example = "potato potato"console.log(example.replace(/pot/, "tom")); 

// "tomato potato"

console.log(example.replace(/pot/g, "tom")); 

// "tomato tomato"

2. 提取唯一值

通过使用 Set 对象和 ... 运算符能够使用唯一值创建一个新数组。

var entries = [1,2,3,4,5,6,7,8,4,3,1] 

var unique_entries = [...new Set(entries)];

console.log(unique_entries);

// [1, 2, 3, 4, 5, 6, 7, 8]