我所不知的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!
*/
这里分享一个平台给你们,如果你想拿高薪,想学 习,想突破瓶颈,想跟别人竞争能取得优势,
想学 习Java技术或者提升Java技术想往Java工程师方面 发展,担心面试不过的,可以加这个Java学习交流: 642830685
· HTMLElement.dataset
在之前我在 HTML 元素上使用自定义数据属性 data-*,但我浑然不知有 API 能够轻松的做读取。 抛开一些特殊的命名限制(看标题链接),其基本上就是横线隔开在 JS 中使用时则用驼峰规则。 所以属性 data-birth-planet 在 JS 中会变成 birthPlanet。
`<div></div>`
读取:
let personEl = document.querySelector('#person');
console.log(person.dataset) // DOMStringMap {name: "john", birthPlanet: "earth"}
console.log(personEl.dataset.name) // john
console.log(personEl.dataset.birthPlanet) // earth
// you can programmatically add more too
personEl.dataset.foo = 'bar';
console.log(personEl.dataset.foo); // bar
我所不知的JS的更多相关文章
- 你所不知道的js的小知识点(1)
1.js调试工具 debugger <div class="container"> <h3>debugger语句会产生一个断点,用于调试程序,并没有实际功能 ...
- 我不知道的js(一)作用域与闭包
作用域与闭包 作用域 什么是作用域 作用域就是一套规则,它负责解决(1)将变量存在哪儿?(2)如何找到变量?的问题 作用域工作的前提 谁赋予了作用域的权利?--js引擎 传统编译语言编译的过程 分词/ ...
- 你所不知道的 JS: null , undefined, NaN, true==1=="1",false==0=="",null== undefined
1 1 1 === 全相等(全部相等) == 值相等(部分相等) demo: var x=0; undefined var y=false; undefined if(x===y){ console ...
- 我总结的js方面你可能不是特别清楚的小知识
!!将一个值方便快速转化为布尔值 console.log( !!window===true ); 不声明第三个变量实现交换 var a=1,b=2; a=[b,b=a][0];//执行完这句代码之后 ...
- 学JS的心路历程 -函式(三)this
this是什么,取决于被呼叫的呼叫地点. 昨天有提到说,呼叫函式时候会传递隐含参数:arguments和this并讲解了arguments,今天我们就来探讨this吧! 什么是this 我们都会呼叫函 ...
- 学习JS的心路历程-类型
前言 之前学JS时候都是靠着谷狗一路跌跌撞撞的学过来,从来没有去翻过MDN的文件,导致留了许多技术债给自己. 最近有幸遇到一位前辈并开始从头学JS,前辈表示学程序不看文件是想作死自己?于是我的第一份功 ...
- 我要成为前端工程师!给 JavaScript 新手的建议与学习资源整理
来源于:http://blog.miniasp.com/post/2016/02/02/JavaScript-novice-advice-and-learning-resources.aspx 今年有 ...
- Beta版本——第五次冲刺博客
我说的都队 031402304 陈燊 031402342 许玲玲 031402337 胡心颖 03140241 王婷婷 031402203 陈齐民 031402209 黄伟炜 031402233 郑扬 ...
- 【Python】闭包Closure
原来这就是闭包啊... 还是上次面试,被问只不知掉js里面的闭包 闭包,没听过啊...什么是闭包 回来查了下,原来这货叫闭包啊...... —————————————————————————————— ...
随机推荐
- kotlin实现流读取
在Java对流的读取是下面的那样,当前不要忘记流的关闭close. // java 代码void someFunc(InputStream in, OutputStream out) throws I ...
- wls12C启用Gzip
https://community.oracle.com/message/14109820 https://docs.oracle.com/middleware/1221/wls/NOTES/what ...
- 三种CSS样式
内联式css样式,直接写在现有的HTML标签中 CSS样式可以写在哪些地方呢?从CSS 样式代码插入的形式来看基本可以分为以下3种:内联式.嵌入式和外部式三种. 内联式css样式表就是把css代码直接 ...
- vue项目如何部署到Tomcat中
vue项目如何部署到Tomcat中 1,假设你要访问的项目名称为'hms' 2,在Tomcat的webapps下创建hms文件夹, 3,配置config/index.js文件,build: {} 选项 ...
- 第七章 SpringCloud之非声明式RestClient:Feign
study-url:https://cloud.spring.io/spring-cloud-static/spring-cloud-netflix/1.4.6.RELEASE/multi/multi ...
- web开发(四) 一次性验证码的代码实现
在网上看见一篇不错的文章,写的详细. 以下内容引用那篇博文.转载于<http://www.cnblogs.com/whgk/p/6426072.html>,在此仅供学习参考之用. 其实实现 ...
- Promise.then链式调用
let a = new Promise((resolve,reject)=>{ resolve(1) }).then((r)=>{console.log(r)}).then(()=> ...
- json中loads()和dumps()的应用
import json s = {'name': 'jack'} #将dict转换成strl = json.dumps(s)print(type(l)) #将str转换成dictm = json.lo ...
- 分布式任务celery
Celery的架构由三部分组成,消息中间件(message broker),任务执行单元(worker)和任务执行结果存储(task result store)组成. 消息中间件 Celery本身不提 ...
- getApplication()和getApplicationContext()区别
二者使用结果相同,我们写个代码分别打印二者返回结果,发现两个方法获取的是同一个对象. public class MainActivity extends Activity { @Override pr ...