10 个编写干净JavaScript 代码的最简单的技巧(适合初学者)_数组


1、合并数组

正常代码:

let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇'].concat(apples);


console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"];

修改后的代码:

let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples]; // <-- here


console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"];
let apples = ['🍎', '🍏'];
let fruits = [...apples, '🥭', '🍌', '🍒']; // <-- here


console.log( fruits );
//=> ["🍎", "🍏", "🥭", "🍌", "🍒"];

2、 从数组中获取值

正常代码:

let apples = ['🍎', '🍏'];
let redApple = apples[0];
let greenApple = apples[1];


console.log( redApple ); //=> 🍎
console.log( greenApple ); //=> 🍏;

使用数组解构的干净代码:

let apples = ['🍎', '🍏'];
let [redApple, greenApple] = apples; // <-- here


console.log( redApple ); //=> 🍎
console.log( greenApple ); //=> 🍏;

3、从对象中获取价值

正常代码:

let user = {
"name": "bytefish",
"age": 99
}


let name = user.name
let age = user.age


console.log( name );
console.log( age );;

使用对象解构的干净代码:

let user = {
"name": "bytefish",
"age": 99
}


let {name, age} = user


console.log( name );
console.log( age );;

4、循环数组

正常代码:

let fruits = ['🍉', '🍊', '🍇', '🍎'];


for (let i = 0; i < fruits.length; i++){
console.log(fruits[i])
};

使用 for of 后的代码:

let fruits = ['🍉', '🍊', '🍇', '🍎'];


for (fruit of fruits) {
console.log(fruit)
};

5、使用箭头函数作为回调

正常代码:

let fruits = ['🍉', '🍊', '🍇', '🍎'];


// Using forEach method
fruits.forEach(function(fruit){
console.log( fruit );
});;

使用箭头函数清理代码:

let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(fruit => console.log( fruit ));;

注意:在处理这个时,箭头函数与普通函数不同。如果你在你的函数中使用它,不要贸然替换它。

6、在数组中查找一项

假设我们需要通过一个对象的属性从一个对象数组中查找一个对象,我们通常使用 for 循环:

let inventory = [
{name: 'Bananas', quantity: 5},
{name: 'Apples', quantity: 10},
{name: 'Grapes', quantity: 2}
];


// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
for (let index = 0; index < arr.length; index++) {


// Check the value of this object property `name` is same as 'Apples'
if (arr[index].name === 'Apples') { //=> 🍎


// A match was found, return this object
return arr[index];
}
}
}


let result = getApples(inventory);
console.log( result )
//=> { name: "Apples", quantity: 10 };

使用 array.find() 清理代码:

let inventory = [
{name: 'Bananas', quantity: 5},
{name: 'Apples', quantity: 10},
{name: 'Grapes', quantity: 2}
];


// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
return arr.find(obj => obj.name === 'Apples'); // <-- here
}


let result = getApples(inventory);
console.log( result )
//=> { name: "Apples", quantity: 10 };

7、将字符串转换为数字

正常代码:

let num = parseInt("10")


console.log( num ) //=> 10
console.log( typeof num ) //=> "number";

通过在字符串前添加 + 来清理代码:

let num = +"10";


console.log( num ) //=> 10
console.log( typeof num ) //=> "number"
console.log( +"10" === 10 ) //=> true;

8、检查无效

在使用变量之前,我们经常需要检查其值是否为空。

正常的方法是使用 if-else。

function getUserRole(role) {
let userRole;


// If role is not falsy value
// set `userRole` as passed `role` value
if (role) {
userRole = role;
} else {


// else set the `userRole` as USER
userRole = 'USER';
}


return userRole;
}


console.log( getUserRole() ) //=> "USER"
console.log( getUserRole('ADMIN') ) //=> "ADMIN";

使用 || 清理代码 :

function getUserRole(role) {
return role || 'USER'; // <-- here
}


console.log( getUserRole() ) //=> "USER"
console.log( getUserRole('ADMIN') ) //=> "ADMIN";

9、字符串连接

正常代码:

let name = 'bytefish';
let message = 'Hi '+ name + '!';;

使用模板文字清洁代码:

let name = 'bytefish';
let message = `Hi ${name}!`;;

10、使用速记

正常代码:

let x = 1


if (x !== '' && x !== null && x !== undefined) {
console.log('x is not nullish')
};

使用速记运算符清洁代码:

let x = 1


if (!!x){
console.log('x is not nullish')
};

总结

以上就是我今天跟你分享的10个简单编写JavaScript的技巧,希望对你有用。

10 个编写干净JavaScript 代码的最简单的技巧(适合初学者)_javascript_02


10 个编写干净JavaScript 代码的最简单的技巧(适合初学者)_fish_03