1. 清除或截断一个数组
通过更改数组的长度(length)这个简单的方法,我们就能清除或者截断一个数组啦:
const arr =[11,22,33,44,55,66];// truncantingarr.length =3;console.log(arr);//=> [11, 22, 33]// clearingarr.length =0;console.log(arr);//=> []console.log(arr[2]);//=> undefined
2. 用解构对象来模拟命名函数
当你需要将一组变量作为参数传递给某个函数时,使用「配置对象」的可能性很高,如下所示:
doSomething({ foo:'Hello', bar:'Hey!', baz:42});function doSomething(config){const foo = config.foo !==undefined? config.foo :'Hi';const bar = config.bar !==undefined? config.bar :'Yo!';const baz = config.baz !==undefined? config.baz :13;// ...}
使用doSomething函数的时候, { foo: 'Hello', bar: 'Hey!', baz: 42 } 这个 Json 作为参数传递了进来,然后在函数中拆解Json给变量赋值。
这是一种古老而有效的模式,它试图模拟 JavaScript中的命名参数。这样处理虽然也行,但是会导致代码不必要的冗长。 借助ES2015的对象解构,你可以避开这种冗长:
function doSomething({ foo ='Hi', bar ='Yo!', baz =13}){// ...}
如果你需要使函数中的参数成为可选参数,那也很简单:
function doSomething({ foo ='Hi', bar ='Yo!', baz =13}={}){// ...}
3.数组的参数结构
使用「对象解构」,拆解内容为数组的字符串,然后进行变量赋值:
const csvFileLine ='1997,John Doe,US,john@doe.com,New York';const{2: country,4: state }= csvFileLine.split(',');
数组中的第2项「US」赋值给了country,第四项「New York」赋值给了state。
4. 包含范围条件的switch语句
以下是在switch语句中使用范围的简单技巧:
function getWaterState(tempInCelsius){let state;switch(true){case(tempInCelsius <=0):state ='Solid';break;case(tempInCelsius >0&& tempInCelsius <100):state ='Liquid';break;default:state ='Gas';}return state;}
5.多个异步函数的异步回调机制
可通过 Promise.all 来等待多个异步函数完成。
await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])
6.创造纯净的对象
你可以创造100%纯净的对象,它不会从Object类继承任何方法(例如:构造函数、toString() 等)。
const pureObject =Object.create(null);console.log(pureObject);//=> {}console.log(pureObject.constructor);//=> undefinedconsole.log(pureObject.toString);//=> undefinedconsole.log(pureObject.hasOwnProperty);//=> undefined
7.JSON代码变格式化字符串
JSON.stringify可以做的不仅仅是将JSON对象变成字符串,也可以用它美化你的JSON输出:
const obj ={foo:{ bar:[11,22,33,44], baz:{ bing:true, boom:'Hello'}}};// The third parameter is the number of spaces used to// beautify the JSON output.JSON.stringify(obj,null,4);// =>"{// => "foo": {// => "bar": [// => 11,// => 22,// => 33,// => 44// => ],// => "baz": {// => "bing": true,// => "boom": "Hello"// => }// => }// =>}"
8.从数组中删除重复的项目
通过包含Spread运算符的ES2015——也就是最新的JS,你可以很容易地从数组中删除重复的项目
const removeDuplicateItems = arr =>[...newSet(arr)];removeDuplicateItems([42,'foo',42,'foo',true,true]);//=> [42, "foo", true]
9.将多维数组降维
通过Spread操作符将二维数组降维是件很容易的事:
const arr =[11,[22,33],[44,55],66];const flatArr =[].concat(...arr);//=> [11, 22, 33, 44, 55, 66]
不幸的是,上述技巧只适用于二维数组。但是通过递归,我们可以将二维以上的数组降维:
function flattenArray(arr){const flattened =[].concat(...arr);return flattened.some(item =>Array.isArray(item))?flattenArray(flattened): flattened;}const arr =[11,[22,33],[44,[55,66,[77,[88]],99]]];const flatArr = flattenArray(arr);//=> [11, 22, 33, 44, 55, 66, 77, 88, 99]
以上就是9个小技巧啦,希望它们能帮助你写出更好更漂亮的JS代码!
零基础成为高薪前端工程师!从零开始跟随 Google、GitHub 学习【前端开发】硅谷课程,挑战原汁原味的硅谷项目,获得硅谷认证证书,点击立即免费体验
web前端开发技术学习_前端开发工程师培训_前端开发入门/进阶课程-优达学城(Udacity)官网 | Udacity