Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the writing skills of JavaScript

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

本文小编为大家详细介绍"JavaScript的写法技巧有哪些",内容详细,步骤清晰,细节处理妥当,希望这篇"JavaScript的写法技巧有哪些"文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

过滤空值

filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

注意: filter() 不会对空数组进行检测。

注意: filter() 不会改变原始数组。

使用 filter() 过滤 "空" 值,如 null、undefined 或空字符串,可以使用 .filter(Boolean) 的缩写方法;

它将所有空值转为 false 并从列表中删除它们,优雅!

const groceries = ['apple', null, 'milk', undefined, 'bread', ''];const cleanList = groceries.filter(Boolean);console.log(cleanList);// 'apple', 'milk', 'bread';数组对象解构

我们经常使用 ES6 的解构,对于一个数组,每项都是一个对象,如果想获得数组第一项的对象的某个值,可以这样写;

const people = [ { name: "Lisa", age: 20, }, { name: "Pete", age: 22, }, { name: "Caroline", age: 60, }];const [{age}] = people;console.log(age);// 20

也可以采用逗号占位的方式指定一个项进行赋值;

const people = [ { name: "Lisa", age: 20, }, { name: "Pete", age: 22, }, { name: "Caroline", age: 60, }];const [, , caroline] = people;console.log(caroline);// {// name: "Caroline",// age: 60,// }

当然,也有常见的对象解构赋值;

const caroline = { firstNm: 'Caroline', ag: 27,};const {firstNm: firstName, ag: age } = caroline;console.log(firstName, age);// Caroline, 27分隔数字

对大数字使用分隔符号,将极大的提高可读性;这是 ES12 的新特性;

const bigNumber = 1_000_000;console.log(bigNumber);// 1000000箭头函数直接返回对象

使用箭头函数返回一个对象,为了和函数的 { 区分开来,在外层包一层 ( 即可解决;

const createPerson = (age, name, nationality) => ({ age, name, nationality,});const caroline = createPerson(27, 'Caroline', 'US');console.log(caroline);// {// age: 27,// name: 'Caroline'// nationality: 'US',// }await 链条

我们可以用 filter 和 map 方法接在 await 方法后形成链条过滤或映射处理获取的数据;

const chainDirectly = (await fetch('https://www.people.com')) .filter(person => age > 20) .filter(person => nationality === 'NL')读到这里,这篇"JavaScript的写法技巧有哪些"文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注行业资讯频道。

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report