几个有趣的 JS 特性

标记语句

foo: {
  console.log('one');
  break foo;
  console.log('这句打印不会被执行');
}
console.log('two');

/*
 * # 输出
 * one
 * two
 */

另外,标记也可以给 for 循环命名。

“void” 运算符

这个运算符其实早就存在了,所有的浏览器都支持!

void 运算符对给定的表达式进行求值,然后返回 undefined。

所以,立即调用表达式就可以这样写:

void function iife() {
    console.log('hello');
}();

// 和下面等效

(function iife() {
    console.log('hello');
})()

高级用法:和 async 一起使用 void

void async function() { 
    try {
        const response = await fetch('air.ghost.io'); 
        const text = await response.text();
        console.log(text);
    } catch(e) {
        console.error(e);
    }
}()

// 或者保持下面的写法

(async () => {
    try {
        const response = await fetch('air.ghost.io'); 
        const text = await response.text();
        console.log(text);
    } catch(e) {
        console.error(e);
    }
})();

逗号运算符

逗号运算符对它的每个操作数求值(从左到右),并返回最后一个操作数的值。

function myFunc() {
  let x = 0;
  return (x += 1, x); // 等价于 return ++x;
}

y = false, true; // 希望在 console 中得到 true
console.log(y); // false,逗号优先级低于赋值

z = (false, true); // 希望在 console 中得到 true
console.log(z); // true,括号中整体返回 true

另一个栗子:

const type = 'man';

const isMale = type === 'man' ? (
    console.log('Hi Man!'),
    true
) : (
    console.log('Hi Lady!'),
    false
);

console.log(`isMale is "${isMale}"`);

HTMLElement.dataset

在此之前我一直对 HTML 元素使用自定义数据属性 data-*,因为我不曾意识到存在一个 API 来方便地查询它们。除了个别的命名限制之外(见上面的链接),它的作用基本就是在 JS 中查询的时候允许你使用驼峰命名法(camelCase)来查询「减号-命名」(dash-case)的属性。所以属性名 data-birth-planet 在 JS 中就变成了 birthPlanet。

可以说相当方便了!

栗子

<div id='person' data-name='john' data-birth-planet='earth'></div>
let personEl = document.querySelector('#person');

console.log(personEl.dataset) // DOMStringMap {name: "john", birthPlanet: "earth"}
console.log(personEl.dataset.name) // john
console.log(personEl.dataset.birthPlanet) // earth

// 你也可以在程序中添加属性
personEl.dataset.foo = 'bar';
console.log(personEl.dataset.foo); // bar
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值