博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
我所不知的JS
阅读量:7060 次
发布时间:2019-06-28

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

几天前在阅读 MDN 文档时我发现了一些我从来不知道的 JS 特性和 API。 下面是一份简短的清单, 无论有用不有用——学习 JS 的道路似乎是没有尽头的。

标签语句

在 JS 中,你可以对 for 循环和代码块起名字... 谁知道呢(显然我不知道)! 稍后你可以在for 循环中对该代码使用 break 或 continue 语句, 同时在代码块中也可以使用 break。

loop1: // labeling "loop1" for (let i = 0; i < 3; i++) { // "loop1"  loop2: // labeling "loop2"  for (let j = 0; j < 3; j++) { // "loop2"     if (i === 1) {        continue loop1; // continues upper "loop1"        // break loop1; // breaks out of upper "loop1"     }     console.log(`i = ${i}, j = ${j}`);  }}/* * # Output* i = 0, j = 0* i = 0, j = 1* i = 0, j = 2* i = 2, j = 0* i = 2, j = 1* i = 2, j = 2*/复制代码

这是一个对代码块命名的例子,在代码块中只能使用 break

foo: { console.log('one'); break foo; console.log('this log will not be executed');}console.log('two');/** # Output* one* two*/复制代码

"void" 操作符

这之前我一直以为我掌握了所有的操作符,直到我看到了这个 从 1996 年就有.的操作符。 所有浏览器都支持也非常的好理解, 用 MDN 的话:

void 操作符执行表达式之后同时返回 undefined

这样可以写出立即执行函数的另一种形式:

void function iife() { console.log('hello');}();// is the same as...(function iife() {   console.log('hello');})()复制代码

对 void 的使用需要注意的是,表达式的执行结果是 空(undefined)!

const word = void function iife() { return 'hello';}();// word is "undefined"const word = (function iife() { return 'hello';})();// word is "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);   }}()// or just stick to this :)(async () => {   try {       const response = await fetch('air.ghost.io');        const text = await response.text();       console.log(text);   } catch(e) {       console.error(e);   }})();复制代码

逗号操作符

在阅读完逗号表达式之后, 我并没有感到我完全理解了它是如何工作的。 引用 MDN 的话:

逗号操作符执行其所有的操作数(从左到右)并返回最后一个操作数的结果。

function myFunc() { let x = 0; return (x += 1, x); // same as return ++x;}y = false, true; // returns true in consoleconsole.log(y); // false (left-most)z = (false, true); // returns true in consoleconsole.log(z); // true (right-most)复制代码

· 与 条件操作符 一起使用

逗号操作符的最后一个结果总是作为条件操作符的结果。 所以你可以在这之前放入任意数量的表达式, 在下面的例子中,我在返回的布尔值之前都放了一句 console log。

const type = 'man';const isMale = type === 'man' ? (   console.log('Hi Man!'),   true) : (   console.log('Hi Lady!'),   false);console.log(`isMale is "${isMale}"`);复制代码

国际化 API

在当前国际化要做好很难, 幸运的是,在大部门浏览器中都有 较好的 API 支持。 其中我所喜欢的其中一项就是日期格式化, 看下面的例子。

const date = new Date();const options = { year: 'numeric',  month: 'long',  day: 'numeric'};const formatter1 = new Intl.DateTimeFormat('es-es', options);console.log(formatter1.format(date)); // 22 de diciembre de 2017const formatter2 = new Intl.DateTimeFormat('en-us', options);console.log(formatter2.format(date)); // December 22, 2017复制代码

管道操作符

在撰写本篇文章时,此功能仅在 Firefox 58+ 使用参数开启, 然而在 Babel 中已经有一个针对此操作符提案的 插件了。 看起来非常好,我很喜欢!

const square = (n) => n * n;const increment = (n) => n + 1;// without pipeline operatorsquare(increment(square(2))); // 25// with pipeline operator2 |> square |> increment |> square; // 25复制代码

值得注意的

· 原子性

原子操作带来了可预测的读写结果,特别是当数据在多个线程中共享时,下一个操作会等待其他操作完成之后才会被执行。 对于主线程和其他 WebWorker 之间保持数据同步来说非常有用。

我很喜欢其他编程语言中的原子特性,例如 Java 中。 我觉得在之后使用 WebWorker 将事务从主线程中转移出来之后会使用得更多。

· Array.prototype.reduceRight

我之前从未见过其使用,因为基本上他就是 Array.prototype.reduce() 和 Array.prototype.reverse() 的结合,对于它的使用应该是比较少见的,如果你需要的话,那这个还是挺合适你的!

const flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) {   return a.concat(b);}, []);// flattened array is [4, 5, 2, 3, 0, 1]复制代码

· setTimeout() 参数

在了解到这个功能之后节省了 .bind() 的使用,这个特性从一开始就有了。

setTimeout(alert, 1000, 'Hello world!');/** # Output (alert)* Hello World!*/function log(text, textTwo) {   console.log(text, textTwo);}setTimeout(log, 1000, 'Hello World!', 'And Mars!');/** # Output* Hello World! And Mars!*/复制代码

· HTMLElement.dataset

在之前我在 HTML 元素上使用自定义数据属性 data-*,但我浑然不知有 API 能够轻松的做读取。 抛开一些特殊的命名限制(看标题链接),其基本上就是横线隔开在 JS 中使用时则用驼峰规则。 所以属性 data-birth-planet 在 JS 中会变成 birthPlanet。

`
`复制代码

读取:

let personEl = document.querySelector('#person');console.log(person.dataset) // DOMStringMap {name: "john", birthPlanet: "earth"}console.log(personEl.dataset.name) // johnconsole.log(personEl.dataset.birthPlanet) // earth// you can programmatically add more toopersonEl.dataset.foo = 'bar';console.log(personEl.dataset.foo); // bar复制代码

结 语

希望你能在JS中像我一样发现新东西。

本文转载自:众成翻译

译者:NimitzDEV

翻译链接:http://zcfy.cc/article/js-things-i-never-knew-existed

你可能感兴趣的文章
关于人工智能,你所需了解的基本知识
查看>>
2019,聊聊Web技术的发展
查看>>
centos7使用kubeadm配置高可用k8s集群的另一种方式
查看>>
深入探索 Kdump
查看>>
three.js 坐标系、camera位置属性、点、线、面
查看>>
kubernetes1.9安装dashboard,以及token认证问题
查看>>
linux tcpdump
查看>>
优秀的GPS定位系统源码对开发者意味着什么
查看>>
ASP.NET (Web) + C#算法 | 生成随机数字序列(随机数字+每个数字取随机不重复的位置和颜色)...
查看>>
理解神经网络:从神经元到RNN、CNN、深度学习
查看>>
我国第一部太赫兹视频合成孔径雷达成功研制
查看>>
外卖新零售品牌佐大狮完成数千万元天使轮融资,高榕资本领投
查看>>
GrooveX研发情感治愈机器人lovot,可与人类完成亲密互动
查看>>
使用kubeadm安装k8s-1.11版本
查看>>
Nginx + Keepalived
查看>>
【翻译】Prometheus 2.0.0 新特性
查看>>
Unity 动态加载Animator Event 事件
查看>>
美联邦调查局 FBI 网站被黑,数千特工信息泄露
查看>>
超燃!Apache Flink 全球顶级盛会强势来袭
查看>>
约你一起来写作
查看>>