天天看点

【译】9个强大的JavaScript技巧

【译】9个强大的JavaScript技巧

我喜欢优化!

但是,如果站点无法在用户的​

​Internet Explorer 11​

​浏览器中运行,他们不会在乎我的优化代码。

我使用​​Endtest​​来创建自动测试,并在跨浏览器的云上执行它们。

​​Netflix​​​使用相同的工具来测试他们的​

​web apps​

​。

你应该查看​​文档​​

下面是9个极其强大的​

​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​

​​对象和​

​Spread​

​运算符就可以创建一个唯一值的数组。

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.数字转字符串

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

var 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);      

5.打乱数组元素

每天我都像喝大了~

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

很简单,使用​

​Spread​

​运算符。

var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries); 
// [1, 2, 5, 6, 7, 9]      
准确来说,所谓的多维数组针对二位数组有效!(译者加)

7.短路条件

我们以下面为例子:

if (available) {
    addToCart();
}      

通过简单地使用变量和函数来缩短它:

available && addToCart()      

8.动态属性名

我一直以为我必须先声明一个对象,然后才能分配动态属性。😢

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

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

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

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]      
var entries = [1, 2, 3, 4, 5, 6, 7]; 
console.log(entries.length); 
// 7
entries.length = 0;   
console.log(entries.length); 
// 0
console.log(entries); 
// []      

继续阅读