12

想让你的代码变得更加优雅吗?

 3 years ago
source link: http://www.cnblogs.com/songyao666/p/14289730.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

作为一名开发人员,工作之外的时间总是在学习新事物。作为前端开发人员必须知道一些使我们的代码如何更优雅,工作更轻松的技巧,让自己的代码写的更加高大上,下面这些技巧获取可以帮助到你。

1. 多个条件判断

// long
if( x === 'a' || x === 'b' || x === 'c' || x === 'd'){
// todo
}

// short
if(['a', 'b', 'c', 'd'].includes(x)){
// todo
}

2. 三目运算符

当我们仅使用一些一对if/esle条件判断时, 可以简单地使用三元运算符来实现. 若有多对if/else条件判断,则不建议使用

// long
let flag
if(x > 10){
flag = true
}else {
flag = false
}
// short
let flag = x > 10 ? true : false

3. 变量声明

当我们要声明两个具有共同值或共同类型的变量时,可以使用此简写形式

// long
let a
let b = 1

// short
let a, b = 1

4. 空/未定义检查和分配默认值

当我们需要创建新变量时, 有时需要检查为其值引用的变量是否为 nullundefined , 可以考虑如下实现:

// long
if(test1 !== null || test1 !== undefined || test1 !== ""){
let test2 = test1;
}else {
let test2 = ''
}

// short
let test2 = test1 || ''

5. 给多个变量赋值

当我们处理多个变量并希望将不同的值分配给不同的变量时,此法非常有用。

//long 
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;

//Short
let [test1, test2, test3] = [1, 2, 3];

6. 赋值运算符的简写

我们在编程中处理很多算术运算符。这是将运算符分配给JavaScript变量的有用技术之一

// long
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;

// short
test1++;
test2--;
test3 *= 20;

7. 真值判断

// long
if (test1 === true)

// short
if (test1)

8. 多条件的与/或运算

//long 
if (test1) {
callMethod();
}

//short
test1 && callMethod();

9. forEath

// long
for (var i = 0; i < testList.length; i++)

// short
testList.forEach(item => console.log(item))

10. 比较返回值

// long
let test;
function checkReturn() {
if (!(test === undefined)) {
return test;
} else {
return callMe('test');
}
}
var data = checkReturn();
console.log(data); //output test
function callMe(val) {
console.log(val);
}

// short
function checkReturn() {
return test || callMe('test');
}

11. 箭头函数

//long 
function add(a, b) {
return a + b;
}
//short
const add = (a, b) => a + b;

12. 短函数调用

// long
function test1() {
console.log('test1');
};
function test2() {
console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
test1();
} else {
test2();
}

// short
(test3 === 1? test1:test2)();

13. switch

我们可以将条件保存在键值对象中,并可以根据条件使用。

// long
switch (data) {
case 1:
test1();
break;

case 2:
test2();
break;

case 3:
test();
break;
// And so on...
}

// short
var data = {
1: test1,
2: test2,
3: test
};

data[something] && data[something]();

14. 默认参数

//long
function add(test1, test2) {
if (test1 === undefined)
test1 = 1;
if (test2 === undefined)
test2 = 2;
return test1 + test2;
}

//short
add = (test1 = 1, test2 = 2) => (test1 + test2);
add() //output: 3

15. 参数必传校验

// long
function hello(obj){
let {name, age} = obj
if(!name){
console.warn('name is null, pls check!')
return ''
}
if(!age){
console.warn('age is null, pls check!')
return ''
}
return `${name}: ${age}`
}

// short
function hello(obj){
let {name = required('name'), age = required('age')} = obj
return `${name}: ${age}`
}

function required(key){
console.warn(`${key} is null, pls check!')
}

16. 扩展运算符

//long
const data = [1, 2, 3];
const test = [4 ,5 , 6].concat(data);


//short
const data = [1, 2, 3];
const test = [4 ,5 , 6, ...data];
console.log(test); // [ 4, 5, 6, 1, 2, 3]

对于克隆, 我们也可以使用扩展运算符

//long
const test1 = [1, 2, 3];
const test2 = test1.slice()

//short
const test1 = [1, 2, 3];
const test2 = [...test1];

17. 模板字符串

如果您厌倦了在单个字符串中使用+来连接多个变量,可以考虑用这种方式

//long
const welcome = 'Hi ' + user + ' ' + name + '.'

//short
const welcome = `Hi ${user} ${name}`;

18. 对象属性赋值

let test1 = 'a'; 
let test2 = 'b';
//Long
let obj = {test1: test1, test2: test2};

//short
let obj = {test1, test2};

19. 字符串转换成数字

//Long
let test1 = parseInt('123');
let test2 = parseFloat('12.3');

//Short
let test1 = +'123';
let test2 = +'12.3';

20. Array.find

当我们确实有一个对象数组并且我们想要根据对象属性查找特定对象时, find 方法确实很有用。

const data = [{
type: 'test1',
name: 'abc'
},
{
type: 'test2',
name: 'cde'
},
{
type: 'test1',
name: 'fgh'
},
]
// long
function findtest1(name) {
for (let i = 0; i < data.length; ++i) {
if (data[i].type === 'test1' && data[i].name === name) {
return data[i];
}
}
}

//shorthand
filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');
console.log(filteredData);

21. 多条件判断

如果我们有代码来检查类型,并且基于类型需要调用不同的方法,我们可以选择使用多个else if或进行切换,有没有更好的呢?

// long
if (type === 'test1') {
test1();
}
else if (type === 'test2') {
test2();
}
else if (type === 'test3') {
test3();
}
else if (type === 'test4') {
test4();
} else {
throw new Error('Invalid value ' + type);
}

// short
const types = {
test1: test1,
test2: test2,
test3: test3,
test4: test4
};

let func = types[type];
(!func) && throw new Error('Invalid value ' + type); func();

22. 索引查找

当我们迭代数组以查找特定值时,我们确实使用 indexOf() 方法,如果我们找到更好的方法呢?让我们看看这个例子。

//long
if(arr.indexOf(item) > -1) { // item found
}
if(arr.indexOf(item) === -1) { // item not found
}

//short
if(~arr.indexOf(item)) { // item found
}
if(!~arr.indexOf(item)) { // item not found
}

按位~运算符 将返回非-1的真实值。取反就像做~一样简单。另外,我们也可以使用 include() 函数:

if (arr.includes(item)) { 
// true if the item found
}

23. Object.entries()

此功能有助于将对象转换为对象数组

const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
/** ouput

[ [ 'test1', 'abc' ],
[ 'test2', 'cde' ],
[ 'test3', 'efg' ]
]

**/

24. Object.values()

const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);
/** Output:

[ 'abc', 'cde']

**/

25. 重复一个字符串多次

要一次又一次地重复相同的字符,我们可以使用 for 循环并将它们添加到同一循环中,但是如果我们有一个简写方法呢?

//long 
let test = '';
for(let i = 0; i < 5; i ++) {
test += 'test ';
}
console.log(str); // test test test test test

//short
'test '.repeat(5);

26. 在数组中查找最大值和最小值

const arr = [1, 2, 3]; 
Math.max(…arr); // 3
Math.min(…arr); // 1

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK