if else 简写_代码要写完整多累来了解一下简写吧

60702fc12c8b8f3c9a3cbb0df269604f.png

初级篇

1、三目运算符

下面是一个很好的例子,将一个完整的 if 语句,简写为一行代码。

const x = 20;
let answer;
if (x > 10) {
    answer = 'greater than 10';
} else {
    answer = 'less than 10';
}

简写为

const answer = x > 10 ? 'greater than 10' : 'less than 10';

2、循环语句

当使用纯 JavaScript(不依赖外部库,如 jQuery 或 lodash)时,下面的简写会非常有用。

for (let i = 0; i < allImgs.length; i++)

简写为

for (let index of allImgs)

下面是遍历数组 forEach 的简写示例:

function logArrayElements(element, index, array) {
  console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[2] = 9

3、声明变量

在函数开始之前,对变量进行赋值是一种很好的习惯。在申明多个变量时:

let x;
let y;
let z = 3;

可以简写为

let x, y, z=3;

4、if 语句

在使用 if 进行基本判断时,可以省略赋值运算符。

if (likeJavaScript === true)

简写为

if (likeJavaScript)

5、十进制数

可以使用科学计数法来代替较大的数据,如可以将 10000000 简写为 1e7。

for (let i = 0; i < 10000; i++) { }

简写为

for (let i = 0; i < 1e7; i++) { }

6、多行字符串

如果需要在代码中编写多行字符串,就像下面这样:

const lorem = 'Lorem ipsum dolor sit amet, consecteturnt'
    + 'adipisicing elit, sed do eiusmod tempor incididuntnt'
    + 'ut labore et dolore magna aliqua. Ut enim ad minimnt'
    + 'veniam, quis nostrud exercitation ullamco laborisnt'
    + 'nisi ut aliquip ex ea commodo consequat. Duis autent'
    + 'irure dolor in reprehenderit in voluptate velit esse.nt'

但是还有一个更简单的方法,只使用引号:

const lorem = `Lorem ipsum dolor sit amet, consectetur
    adipisicing elit, sed do eiusmod tempor incididunt
    ut labore et dolore magna aliqua. Ut enim ad minim
    veniam, quis nostrud exercitation ullamco laboris
    nisi ut aliquip ex ea commodo consequat. Duis aute
    irure dolor in reprehenderit in voluptate velit esse.`

高级篇

1、变量赋值

当将一个变量的值赋给另一个变量时,首先需要确保原值不是 null、未定义的或空值。

可以通过编写一个包含多个条件的判断语句来实现:

if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
     let variable2 = variable1;
}

或者简写为以下的形式

const variable2 = variable1  || 'new';

2、默认值赋值

如果预期参数是 null 或未定义,则不需要写六行代码来分配默认值。我们可以只使用一个简短的逻辑运算符,只用一行代码就能完成相同的操作。

let dbHost;
if (process.env.DB_HOST) {
  dbHost = process.env.DB_HOST;
} else {
  dbHost = 'localhost';
}

简写为

const dbHost = process.env.DB_HOST || 'localhost';

3、对象属性

ES6 提供了一个很简单的办法,来分配属性的对象。如果属性名与 key 名相同,则可以使用简写。

const obj = { x:x, y:y };

简写为

const obj = { x, y };

4、箭头函数

经典函数很容易读写,但是如果把它们嵌套在其它函数中进行调用时,整个函数就会变得有些冗长和混乱。这时候可以使用箭头函数来简写:

function sayHello(name) {
  console.log('Hello', name);
}
 
setTimeout(function() {
  console.log('Loaded')
}, 2000);
 
list.forEach(function(item) {
  console.log(item);
});

简写为

sayHello = name => console.log('Hello', name);
setTimeout(() => console.log('Loaded'), 2000);
list.forEach(item => console.log(item));

5、隐式返回值

返回值是我们通常用来返回函数最终结果的关键字。只有一个语句的箭头函数,可以隐式返回结果(函数必须省略括号({ }),以便省略返回关键字)。

要返回多行语句(例如对象文本),需要使用()而不是{ }来包裹函数体。这样可以确保代码以单个语句的形式进行求值。

function calcCircumference(diameter) {
  return Math.PI * diameter
}

简写为

calcCircumference = diameter => (
  Math.PI * diameter;
)

6、默认参数值

可以使用 if 语句来定义函数参数的默认值。ES6 中规定了可以在函数声明中定义默认值。

function volume(l, w, h) {
  if (w === undefined)
    w = 3;
  if (h === undefined)
    h = 4;
  return l * w * h;
}

简写为

volume = (l, w = 3, h = 4 ) => (l * w * h);
volume(2) //output: 24

7、模板字符串

过去我们习惯了使用“+”将多个变量转换为字符串,但是有没有更简单的方法呢?

ES6 提供了相应的方法,我们可以使用反引号和 $ { } 将变量合成一个字符串。

const welcome = 'You have logged in as ' + first + ' ' + last + '.'
const db = 'http://' + host + ':' + port + '/' + database;

简写为

const welcome = `You have logged in as ${first} ${last}`;
const db = `http://${host}:${port}/${database}`;

8、解构赋值

解构赋值是一种表达式,用于从数组或对象中快速提取属性值,并赋给定义的变量。

在代码简写方面,解构赋值能达到很好的效果。

const observable = require('mobx/observable');
const action = require('mobx/action');
const runInAction = require('mobx/runInAction');
const store = this.props.store;
const form = this.props.form;
const loading = this.props.loading;
const errors = this.props.errors;
const entity = this.props.entity;

简写为

import { observable, action, runInAction } from 'mobx';
const { store, form, loading, errors, entity } = this.props;

甚至可以指定自己的变量名:

const { store, form, loading, errors, entity:contact } = this.props;

9、展开运算符

展开运算符是在 ES6 中引入的,使用展开运算符能够让 JavaScript 代码更加有效和有趣。

使用展开运算符可以替换某些数组函数。

// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);
 
// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice( )

简写为

// joining arrays
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]
 
// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];

总结

上述是一些常用的 JavaScript 简写技巧,建议不熟悉的新手少用等熟悉了再想着偷懒是最好的。如果有其它未提及的简写技巧,也欢迎大家补充。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值