首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

5 分钟掌握 JavaScript 实用窍门

互联网人学习成长社群

第五期Web全栈架构师火爆报名中~

一开始 JavaScript 只是为网页增添一些实时动画效果,现在 JS 已经能做到前后端通吃了,而且还是年度流行语言。本文分享几则 JS 小窍门,可以让你事半功倍 !

1. 删除数组尾部元素

一个简单方法就是改变数组的length值:

constarr=[11,22,33,44,55,66];

// truncanting

arr.length=3;

console.log(arr);//=> [11, 22, 33]

// clearing

arr.length=;

console.log(arr);//=> []

console.log(arr[2]);//=> undefined

2. 使用对象解构(object

destructuring)来模拟命名参数

如果需要将一系列可选项作为参数传入函数,你很可能会使用对象(Object)来定义配置(Config)。

doSomething({foo:'Hello',bar:'Hey!',baz:42});

functiondoSomething(config){

constfoo=config.foo!==undefined?config.foo:'Hi';

constbar=config.bar!==undefined?config.bar:'Yo!';

constbaz=config.baz!==undefined?config.baz:13;

// ...

}

不过这是一个比较老的方法了,它模拟了 JavaScript 中的命名参数。

在 ES 2015 中,你可以直接使用对象解构:

functiondoSomething({foo='Hi',bar='Yo!',baz=13}){

// ...

}

让参数可选也很简单:

functiondoSomething({foo='Hi',bar='Yo!',baz=13}={}){

// ...

}

3. 使用对象解构来处理数组

可以使用对象解构的语法来获取数组的元素:

const{2:country,4:state}=csvFileLine.split(',');

4. 在 Switch 语句中使用范围值

可以这样写满足范围值的语句:

functiongetWaterState(tempInCelsius){

letstate;

switch(true){

case(tempInCelsius):

state='Solid';

break;

case(tempInCelsius>&&tempInCelsius100):

state='Liquid';

break;

default:

state='Gas';

}

returnstate;

}

5. await 多个 async 函数

在使用 async/await 的时候,可以使用 Promise.all 来 await 多个 async 函数

awaitPromise.all([anAsyncCall(),thisIsAlsoAsync(),oneMore()])

6. 创建 pure objects

你可以创建一个 100% pure object,它不从Object中继承任何属性或则方法(比如constructor, toString()等)

constpureObject=Object.create(null);

console.log(pureObject);//=> {}

console.log(pureObject.constructor);//=> undefined

console.log(pureObject.toString);//=> undefined

console.log(pureObject.hasOwnProperty);//=> undefined

7. 格式化 JSON 代码

JSON.stringify除了可以将一个对象字符化,还可以格式化输出 JSON 对象。

constobj={

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 操作,可以很容易将重复的元素移除:

constremoveDuplicateItems=arr=>[...new Set(arr)];

removeDuplicateItems([42,'foo',42,'foo',true,true]);

//=> [42, "foo", true]

9. 平铺多维数组

使用 Spread 操作平铺嵌套多维数组:

constarr=[11,[22,33],[44,55],66];

constflatArr=[].concat(...arr);//=> [11, 22, 33, 44, 55, 66]

不过上面的方法仅适用于二维数组,但是通过递归,就可以平铺任意维度的嵌套数组了:

functionflattenArray(arr){

constflattened=[].concat(...arr);

returnflattened.some(item=>Array.isArray(item))?

flattenArray(flattened):flattened;

}

constarr=[11,[22,33],[44,[55,66,[77,[88]],99]]];

constflatArr=flattenArray(arr);

//=> [11, 22, 33, 44, 55, 66, 77, 88, 99]

希望这些小技巧能帮助你写好 JavaScript, 有需要的收藏吧~

有你想看的精彩

感谢您的阅读,如果你觉得我的公众号还不错,请多帮我推荐给你的朋友,多谢了。

前端大牛爱好者:每天一篇前端技术文章,不定时前端干货发送

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20180622B1EIAP00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券