博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
9 个功能强大的 JavaScript 技巧
阅读量:4117 次
发布时间:2019-05-25

本文共 1802 字,大约阅读时间需要 6 分钟。

英文 | https://dev.to/razgandeanu/9-extremely-powerful-javascript-hacks-4g3p

译文 | https://www.html.cn/web/javascript/14872.html

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, 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);// 5console.log(typeof converted_number); // string

4、将字符串转换为数字

我们需要的只是 + 运算符。

请注意它仅适用于“字符串数字”。

the_string = "123";console.log(+the_string);// 123the_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 调整/清空数组

我们基本上覆盖了数组的 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); // []

本文完~

转载地址:http://bdbpi.baihongyu.com/

你可能感兴趣的文章
OpenCV gpu模块样例注释:video_reader.cpp
查看>>
OpenCV meanshift目标跟踪总结
查看>>
就在昨天,全球 42 亿 IPv4 地址宣告耗尽!
查看>>
听说玩这些游戏能提升编程能力?
查看>>
如果你还不了解 RTC,那我强烈建议你看看这个!
查看>>
沙雕程序员在无聊的时候,都搞出了哪些好玩的小玩意...
查看>>
Mysql复制表以及复制数据库
查看>>
Linux系统编程——线程池
查看>>
Linux C++线程池实例
查看>>
matplotlib.pyplot.plot()参数详解
查看>>
MFC矩阵运算
查看>>
ubuntu 安装mysql
查看>>
c# 计算器
查看>>
C# 简单的矩阵运算
查看>>
gcc 常用选项详解
查看>>
c++输出文件流ofstream用法详解
查看>>
firewalld的基本使用
查看>>
Linux下SVN客户端使用教程
查看>>
Linux分区方案
查看>>
nc 命令详解
查看>>