JavaScript 更加简洁的技巧,使你的代码优雅无瑕

JavaScript 从诞生以来就在不断进化。毫无疑问,JS 是最受欢迎的语言之一,这一地位还会长期保持下去。对于前端开发人员来说那些简洁的技巧,使你的代码优雅无瑕。本篇文章就推荐一些常用简洁方案。

JavaScript 更加简洁的技巧,使你的代码优雅无瑕_第1张图片

阅读掌握时间:5分钟

1.当遇到多个条件时如何处理?

const conditions = [“Condition 2”,“Condition String2”];
someFunction(str){
if(str.includes(“someValue1”) || str.includes(“someValue2”)){
return true
} else {
return false
}
}
一种更干净的方法是:
someFunction(str){
const conditions = [“someValue1”,“someValue2”];
return conditions.some(condition=>str.includes(condition));
}
2.避免过多的函数参数

function myFunction(employeeName,jobTitle,yrExp,majorExp){
return ${employeeName} is working as ${jobTitle} with ${yrExp} years of experience in ${majorExp}
}
console.log(myFunction(“John”,“Project Manager”,12,“Project Management”))
// output be like John is working as Project Manager with 12 year of experience in Project Management

这是一种更清洁的方法:
function myFunction({employeeName,jobTitle,yrExp,majorExp}){
return ${employeeName} is working as ${jobTitle} with ${yrExp} years of experience in ${majorExp}
}
const mockTechPeople = {
employeeName:“John”,
jobTitle:“Project Manager”,
yrExp:12,
majorExp:“Project Management”
}
console.log(myFunction(mockTechPeople))
// output be like John is working as Project Manager with 12 year of experience in Project Management
// 看起来舒服多了吧~
3.使用Object.assign设置默认对象

这看起来是不是很繁琐:
const someObject = {
title: null,
subTitle: “Subtitle”,
buttonColor: null,
disabled: true
};
function createOption(someObject) {
someObject.title = someObject.title || “Default Title”;
someObject.subTitle = someObject.subTitle || “Default Subtitle”;
someObject.buttonColor = someObject.buttonColor || “blue”;
someObject.disabled = someObject.disabled !== undefined ? someObject.disabled : true;
return someObject
}
console.log(createOption(someObject));
// {title: ‘Default Title’, subTitle: ‘Subtitle’, buttonColor: ‘blue’, disabled: true}
这种方法看起来更好:
const someObject = {
title: null,
subTitle: “Subtitle”,
buttonColor: null,
disabled: true
};
function creteOption(someObject) {
const newObject = Object.assign({
title: “Default Title”,
subTitle: “Default Subtitle”,
buttonColor: “blue”,
disabled: true
},someObject)
return newObject
}
console.log(creteOption(someObject));
4.清空或截断数组

在不重新给数组赋值的情况下,清空或截断数组的最简单方法是更改其 length 属性值:

const arr = [11, 22, 33, 44, 55, 66];
// truncanting
arr.length = 3;
console.log(arr); //=> [11, 22, 33]
// clearing
arr.length = 0;
console.log(arr); //=> []
console.log(arr[2]); //=> undefine
5.使用对象解构来处理数组

可以使用对象解构将数组项分配给各个变量:

const csvFileLine = ‘1999,And Ming,UA,[email protected],NewYork’;
const { 2: country, 4: state } = csvFileLine.split(’,’);
6.使用 async/await 来 await多个async函数

可以使用 Promise.all 来 await 多个 async(异步)函数。
await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])
7.创建纯(pure)对象

您可以创建一个 100% 纯对象,它不会从 Object 继承任何属性或方法(例如,constructor,toString() 等)。

const pureObject = Object.create(null);
console.log(pureObject); //=> {}
console.log(pureObject.constructor); //=> undefined
console.log(pureObject.toString); //=> undefined
console.log(pureObject.hasOwnProperty); //=> undefined
8.格式化JSON代码

JSON.stringify 不仅可以简单地将对象转化为字符串。你也可以用它来格式化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”
// => }
// => }
// =>}

9.从数组中删除重复元素(数组去重)

通过使用通过使用集合语法和 Spread(展开)运算符,您可以轻松地从数组中删除重复项:

const removeDuplicateItems = arr => […new Set(arr)];
removeDuplicateItems([42, ‘foo’, 42, ‘foo’, true, true]);
//=> [42, “foo”, true]
10.平铺多维数组

使用 Spread(展开),可以很容易去平铺嵌套多维数组:

const arr = [11, [22, 33], [44, 55], 66];
const flatArr = [].concat(…arr); //=> [11, 22, 33, 44, 55, 66]
可惜,上面的方法仅仅适用于二维数组。不过,通过递归,我们可以平铺任意维度的嵌套数组。

unction 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]

如果你觉得这篇内容对你挺有启发,我想邀请你帮我三个小忙:
点个「在看」,让更多的人也能看到这篇内容(喜欢不点在看,都是耍流氓 -_-)
欢迎加我微信「 vx172537 」拉你进技术群,长期交流学习…
关注公众号「前端开发屋」,持续为你推送精选好文,也可以加我为好友,随时畅谈。

你可能感兴趣的:(javascript)