4 分钟内您不知道的 8 个简洁的 Javascript 技巧。
简介
Javascript 是一种功能强大的编程语言,尤其适用于 Web 开发,它用于创建和控制动态网站内容,即任何在屏幕上移动、刷新或其他变化的内容,无需手动重新加载网页。在过去的五年里,Javascript 因其简洁易用、功能丰富以及众多软件包而声名鹊起。闲话少叙,让我们开始深入探讨吧。
1. 字符串转数字
现在,只需使用+
符号即可轻松将字符串转换为数字。与旧方法不同,使用+
运算符更加简洁易用。
my_string = "123";
console.log(+my_string);
// 123
my_string = "amazing";
console.log(+my_string);
// NaN
请注意,它仅适用于string numbers
您在上面的示例中看到的情况。
2. 数字转换为字符串
您可以以更简单的方式将数字转换为字符串,而无需使用 JavaScript 内置toString()
方法。
看看这个:
let converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number);
// string
3. 获取唯一值我们可以从数组中提取唯一值,即通过简单地使用和
删除数组中的重复值。Set object
Spread operator
这是一个简单的演示
let array_values = [1, 3, 3, 4, 5, 6, 6, 6,8, 4, 1]
let unique_values = [...new Set(array_values )];
console.log(unique_values );
// [1,3, 4, 5, 6, 8]
4. 全部替换
我们通常知道string.replace
方法“在第一次出现时替换”。无论如何,JavaScript 中的正则表达式可以用来替换字符串中的特定内容。
在我们的示例中,我们将使用全局正则表达式/g
来替换字符串的所有出现。
let replace_string = "Visit stunnitysoft. stunnitysoft is a software company";
console.log(replace_string.replace(/stunnity/, "Micro"));
// "Visit Microsoft. stunnitysoft is a software company"
console.log(replace_string.replace(/stunnity/g, "Micro"));
// "Visit Microsoft. Microsoft is a software company"
5. 可选链
可选链运算符(?.)
允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。
- 摘自MDN DOCS
让我们考虑一下表达式a?.b
。
a.b
如果a
是not null
且,则该表达式计算结果为not undefined
,否则计算结果为undefined
。
您还可以多次链接此操作,例如a?.b?.c
如果a
是undefined
或null
,则此表达式的计算结果为undefined
否则,如果b
是undefined
或null
,则此表达式的计算结果为undefined
否则,此表达式的计算结果为a.b.c
句法
obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)
6. 空值合并运算符
空值合并运算符(??)
是一个逻辑运算符,当其左侧操作数为空或未定义时,返回其右侧操作数,否则返回其左侧操作数。
- 摘自MDN DOCS
考虑表达式a ?? b
。b
如果a
是null
或undefined
,则计算结果为 ;否则,计算结果为a
7. 逻辑与(&&)和逻辑或(||)运算符
逻辑与 (&&) 运算符
假设我们有以下表达式,其中b
和c
是表达式。
b && c
c
仅当为真时,才会将其评估为的值b
,否则,它将被评估为的值b
。
- 如果
b
是falsy
,那么表达式c
甚至不会被评估。 - 这称为短路评估。
- 这在使用 React 时非常有用。
逻辑或 (||) 运算符
假设我们有以下表达式,其中b
和c
是表达式。
b || c
b
如果b
为,则其值将被评估为truthy
,否则,其值将被评估为c
。
- 短路评估也发生在这里。
- 如果
b
是truthy
,那么表达式c
甚至不会被评估。 - 这在 React 中也经常使用。
8. 使用长度来调整数组大小和清空数组
在 javascript 中,我们可以覆盖内置方法length
并为其分配您选择的值。
让我们考虑以下示例:
let array_values= [1, 2, 3, 4, 5, 6, 7, 8];
console.log(array_values.length);
// 8
array_values.length = 5;
console.log(array_values.length);
// 5
console.log(array_values);
// [1, 2, 3, 4,5]
清空数组
let array_values= [1, 2, 3, 4, 5, 6, 7,8];
console.log(array_values.length);
// 8
array_values.length = 0;
console.log(array_values.length);
// 0
console.log(array_values);
// []
注意:不建议将长度设置为0
,因为这可能会导致内存泄漏。为了从内存中清除数组中的对象,需要显式地删除它们。
结论
如你所见,我们无需编写太多代码,就完成了许多强大的功能。不妨运用这些 JavaScript 技巧,它们将使你的代码更加简洁易维护。
这篇文章太长了,不过谢谢你坚持看到最后
😊。希望这篇文章对你有帮助,如果有用的话,请分享给其他觉得有用的人。欢迎提出建议,或者在推特或领英上给我留言。