8个强大的JavaScript技巧

1.全部替换

我们知道string.replace()函数只能替换第一次出现的情况。你可以在正则表达式的末尾添加/g来替换所有出现的内容。

let example = "potato potato";
console.log(example.replace(/pot/, "tom")); 
// "tomato potato"
console.log(example.replace(/pot/g, "tom")); 
// "tomato tomato"

2.提取唯一值

我们可以仅仅通过Set对象和Spread运算符就可以创建一个唯一值的数组。

let entries = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1]
let unique_entries = [...new Set(entries)];
console.log(unique_entries);
// [1, 2, 3, 4, 5, 6, 7, 8]

3.数字转字符串

我们只需要使用带空引号集的串联运算符即可。

let converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number); 
// string

4.字符串转数字

我们只需要+运算符。

请注意这点,因为它仅适用于“字符串数字”。

the_string = "123";
console.log(+the_string);
// 123

the_string = "hello";
console.log(+the_string);
// NaN

5.打乱数组元素

let 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.碾平多维数组

很简单,使用Spread运算符。

var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries); 
// [1, 2, 5, 6, 7, 9]

准确来说,所谓的多维数组针对二位数组有效!

7.动态属性名

const dynamic = 'flavour';
var item = {
    
    
    name: 'Coke',
    [dynamic]: 'Cherry'
}
console.log(item); 
// { name: "Coke", flavour: "Cherry" }

8.使用长度调整/清空数组

我们基本上重写了数组的长度。

如果我们想调整数组:

let 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]

如果你想清空数组:

let entries = [1, 2, 3, 4, 5, 6, 7]; 
console.log(entries.length); 
// 7  
entries.length = 0;   
console.log(entries.length); 
// 0 
console.log(entries); 
// []

猜你喜欢

转载自blog.csdn.net/qq_44880095/article/details/113619003