JS 中 9 个强大主流写法(各种 Hack 写法)

互联网 20-5-15

1. 全局替换

我们知道,字符串函数 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, 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); // NaN

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

只需使用扩展运算符。

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. 使用 length 去调整或清空一个数组

我们主要重写了数组的长度。

如果我们想要调整数组的大小:

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);  // []

推荐教程:《JS教程》

以上就是JS 中 9 个强大主流写法(各种 Hack 写法)的详细内容,更多内容请关注技术你好其它相关文章!

来源链接:
免责声明:
1.资讯内容不构成投资建议,投资者应独立决策并自行承担风险
2.本文版权归属原作所有,仅代表作者本人观点,不代表本站的观点或立场
标签: js
上一篇:php获取远程图片并下载保存到本地的方法分析 下一篇:利用js实现表格隔行换色效果

相关资讯