我所不知的JS
点击上方“程序人生”,选择“置顶公众号”
第一时间关注程序猿(媛)身边的故事
几天前在阅读 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 console
console.log(y); // false (left-most)
z = (false, true); // returns true in console
console.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 2017
const 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 operator
square(increment(square(2))); // 25
// with pipeline operator
2 |> 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 元素上使用自定义数据属性 src="http://img5.shadafang.com/img.php?http://mmbiz.qpic.cn/mmbiz_png/1hReHaqafadUzllibDXFBLnoOXW9b20aQ07UfPb2WbSPMqlGlmniaHEEHiazqUA9t2HL26SjDhv63wA9mNTTLicnoQ/0?wx_fmt=png" />
- 原来避孕药有这5个用处!很多女人一个也不知道
- 十年DNF将毁于金币限制?不说不知道,原来金币系统关乎太多!
- 这四个女英雄让周瑜连来抱,不知火舞最般配,甄姬很不情愿
- 一恋爱就不知所措的四大星座,看看哪些星座上榜了?
- 买房的小心了,年后有大变动,不看你们不知道
- 刘邦被困白登山,陈平奇计解围,后人至今不知是何计
- 【Yui宝宝小课堂】1000----单挑教程:慢打
- 扑克花边:超级碗,潜泳,越南
- 【Yui宝宝小课堂】1001----从四条中得到价值
- 他是岭南盆景的一颗亮丽新星