大多数开发人员不知道的 5 个很酷的 JavaScript 功能

2025-06-10

大多数开发人员不知道的 5 个很酷的 JavaScript 功能

你可以用 JavaScript 以不同的方式完成同一件事。随着每个新 ECMAScript 规范的发布,都会添加新的方法和运算符,以使代码更简洁、更易读。

代码

1. Object.entries

大多数开发者使用Object.keys方法来遍历对象。此方法仅返回对象键的数组,不返回值。您可以使用Object.entries来获取键和值。

const person = {
  name: 'Nick',
  age: 27
};
Object.keys(person); // ['name', 'age']
Object.entries(data); // [['name', 'Nick'], ['age', 27]]
Enter fullscreen mode Exit fullscreen mode

要迭代一个对象,我们可以执行以下操作:

Object.keys(person).forEach((key) => {
  console.log(`${key} is ${person[key]}`);
});
// using records to get the key and value
Object.entries(person).forEach(([key, value]) => {
  console.log(`${key} is ${value}`);
});
// expected result:
// name is Nick
// age is 27
Enter fullscreen mode Exit fullscreen mode

上述两种方法都返回相同的结果,但Object.entries可以轻松获取键值对。

2. replaceAll 方法

在 JavaScript 中,要用另一个字符串替换所有出现的字符串,我们需要使用如下正则表达式:

const str = 'Red-Green-Blue';

// replaces only the first entry

str.replace('-', ' '); // Red Green-Blue

// use a regular expression to replace all entries
str.replace(/\-/g, ' '); // Red Green Blue
Enter fullscreen mode Exit fullscreen mode

但在 ES12 中, String.prototype 中添加了一个新的 replaceAll方法,该方法用另一个字符串值替换所有出现的字符串:

str.replaceAll('-', ' '); // Red Green Blue
Enter fullscreen mode Exit fullscreen mode

3. 数字分隔符

您可以使用下划线“_”作为数字分隔符,以简化数字中零的数量的计算。

// less readable
const billion = 1000000000;
// more readable
const readableBillion = 1000_000_000;
console.log(readableBillion) // returns 1000000000
Enter fullscreen mode Exit fullscreen mode

分隔符也可以与 BigInt 数字一起使用,如下例所示:

const trillion = 1000_000_000_000n;
console.log(trillion); // 1000000000000
Enter fullscreen mode Exit fullscreen mode

这使得数字更具可读性。

4. document.designMode

设计模式与前端 JavaScript 链接,可让您编辑页面上的任何内容。只需打开浏览器控制台并输入以下内容:

document.designMode = 'on';
Enter fullscreen mode Exit fullscreen mode

这对设计师来说很有用,因为他们不需要每次都改变代码来匹配屏幕上的变化。

5.逻辑赋值运算符

逻辑赋值运算符是逻辑运算符&&、||、??和赋值运算符=的组合

const a = 1;
const b = 2;
a &&= b;
console.log(a); // returns 2
// the above statement is equivalent to a && (a = b);
// OR another way
if (a) {
  a = b
}
Enter fullscreen mode Exit fullscreen mode

这里检查a的值是否为 true,如果是,则更新其值。逻辑或 //运算符也可以实现同样的效果。

const a = null;
const b = 3;
a ||= b;
console.log(a); // returns 3
// the above statement is equivalent to
a || (a = b);
Enter fullscreen mode Exit fullscreen mode

并且还可以借助操作员??

const a = null;
const b = 3;
a ??= b;
console.log(a); // returns 3
// the above statement is equivalent to
if (a === null || a === undefined) {
  a = b;
}
Enter fullscreen mode Exit fullscreen mode

运算符??仅检查空值或未定义值。

请注意,自ES 12/ES 2021以来已添加逻辑赋值运算符

结论

这些技巧和功能可以加速开发人员的工作,它们的使用不仅是必要的,而且非常有用。继续探索该语言的隐藏特性,学习各种技巧,提升你的技能。

鏂囩珷鏉ユ簮锛�https://dev.to/ra1nbow1/5-cool-javascript-features-that-most-developers-dont-know-about-5b7f
PREV
7 种现代数据库类型:用途、优点和缺点 关系型 SQL 数据库 面向文档的数据库 内存数据库 宽列数据库 列式数据库 搜索引擎 图形数据库 结论
NEXT
Linux 101 - 操作系统之王👑