JavaScript 很少有人知道的最隐僻的14个特性

1. 标签模板字符串(Tagged Template Literals)
  • 允许你将函数应用于模板字符串,这可以用于解析模板字符串中的变量。
function highlight(strings, ...values) {
  return strings.reduce((acc, str, i) => {
    return `${acc}${str}<em>${values[i] || ''}</em>`;
  }, '');
}
const name = 'World';
console.log(highlight`Hello, ${name}!`); // 输出: Hello, <em>World</em>!
2. 解构赋值的默认值
  • 可以在解构赋值时为变量提供默认值。
const { name = 'Anonymous' } = { name: undefined };
console.log(name); // 输出: Anonymous
3. 逗号操作符
  • 允许你将多个表达式放在一个语句中,并返回最后一个表达式的值。
const a = 1;
const b = (a++, a);
console.log(b); // 输出: 2
4. 函数的 length 属性
  • 表示函数期望接收的参数个数。
function foo(a, b, c) {}
console.log(foo.length); // 输出: 3
5. 函数的 arguments 属性
  • 包含调用函数时传递的所有参数的类数组对象。
function foo() {
  console.log(arguments);
}
foo(1, 2, 3); // 输出: [1, 2, 3]
6. with 语句
  • 允许你将代码块内的变量查找限定在指定的对象中。
with (Math) {
  console.log(min(1, max(0, 5)));
} // 输出: 1
7. 对象字面量中的属性值缩写
  • 允许你省略属性的值,如果属性名和变量名相同。
const x = 10, y = 20;
const obj = { x, y };
console.log(obj); // 输出: { x: 10, y: 20 }
8. Proxy 对象
  • 用于创建一个对象的代理,从而可以拦截和自定义对象的基本操作。
const handler = {
  get: function(obj, prop) {
    return prop in obj ? obj[prop] : 37;
  }
};
const p = new Proxy({}, handler);
p.a = 1;
console.log(p.a, p.b); // 输出: 1 37
9. Reflect API
  • 提供了一组静态方法,对应于Proxy对象的拦截操作,但以函数的形式存在。
const obj = { x: 1 };
console.log(Reflect.get(obj, 'x')); // 输出: 1
10. BigInt 类型
  • 允许你安全地表示、操作大整数。
const bigNumber = BigInt(1234567890123456789012345678901234567890n);
console.log(bigNumber); // 输出: 1234567890123456789012345678901234567890n
11. Symbol 类型
  • 一种新的原始数据类型,表示一个独一无二的、不可变的、原始值。
const uniqueSymbol = Symbol('mySymbol');
const obj = {
  [uniqueSymbol]: 'This is unique!'
};
console.log(obj[uniqueSymbol]); // 输出: This is unique!
12. 动态导入(Dynamic Imports)
  • 一种新的原始数据类型,表示一个独一无二的、不可变的、原始值。
const uniqueSymbol = Symbol('mySymbol');
const obj = {
  [uniqueSymbol]: 'This is unique!'
};
console.log(obj[uniqueSymbol]); // 输出: This is unique!
13. 可选链操作符(Optional Chaining Operator)
  • 允许你读取位于连接对象链深处的属性而不必显式地验证链中的每一环是否存在。
const value = obj?.property?.method();
14. 空值合并操作符(Nullish Coalescing Operator)
  • 提供了一种方式,当左侧表达式为 null 或 undefined 时,返回右侧表达式的值。
const foo = null ?? 'default string';
console.log(foo); // 输出: 'default string'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

**之火

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值