1.三元操作符

当想写 if...else 语句时,使用三元操作符来代替。

  1. const x = 20;

  2. let answer;

  3. if (x > 10) {

  4.    answer = 'is greater';

  5. } else {

  6.    answer = 'is lesser';

  7. }

简写:

  1. const answer = x > 10 ? 'is greater' : 'is lesser';

也可以嵌套if语句:

  1. const big = x > 10 ? " greater 10" : x

2.短路求值简写方式

当给一个变量分配另一个值时,想确定源始值不是null,undefined或空值。可以写撰写一个多重条件的if语句。

  1. if (variable1 !== null || variable1 !== undefined || variable1 !== '') {

  2.     let variable2 = variable1;

  3. }

或者可以使用短路求值方法:

  1. const variable2 = variable1  || 'new';

3.声明变量简写方法

  1. let x;

  2. let y;

  3. let z = 3;

简写方法:

  1. let x, y, z=3;

4.if存在条件简写方法

  1. if (likeJavaScript === true)

简写:

  1. if (likeJavaScript)

只有likeJavaScript是真值时,二者语句才相等。

如果判断值不是真值,则可以这样:

  1. let a;

  2. if ( a !== true ) {

  3. // do something...

  4. }

简写:

  1. let a;

  2. if ( !a ) {

  3. // do something...

  4. }

5.JavaScript循环简写方法

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

简写: for(letindexinallImgs)也可以使用Array.forEach:

  1. function logArrayElements(element, index, array) {

  2.  console.log("a[" + index + "] = " + element);

  3. }

  4. [2, 5, 9].forEach(logArrayElements);

  5. // logs:

  6. // a[0] = 2

  7. // a[1] = 5

  8. // a[2] = 9

6.短路评价

给一个变量分配的值是通过判断其值是否为null或undefined,则可以:

  1. let dbHost;

  2. if (process.env.DB_HOST) {

  3.  dbHost = process.env.DB_HOST;

  4. } else {

  5.  dbHost = 'localhost';

  6. }

简写:

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

7.十进制指数

当需要写数字带有很多零时(如10000000),可以采用指数(1e7)来代替这个数字: for(leti=0;i<10000;i++){}简写:

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

  2. // 下面都是返回true

  3. 1e0 === 1;

  4. 1e1 === 10;

  5. 1e2 === 100;

  6. 1e3 === 1000;

  7. 1e4 === 10000;

  8. 1e5 === 100000;

8.对象属性简写

如果属性名与key名相同,则可以采用ES6的方法:

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

简写:

  1. const obj = { x, y };

9.箭头函数简写

传统函数编写方法很容易让人理解和编写,但是当嵌套在另一个函数中,则这些优势就荡然无存。

  1. function sayHello(name) {

  2.  console.log('Hello', name);

  3. }

  4. setTimeout(function() {

  5.  console.log('Loaded')

  6. }, 2000);

  7. list.forEach(function(item) {

  8.  console.log(item);

  9. });

简写:

  1. sayHello = name => console.log('Hello', name);

  2. setTimeout(() => console.log('Loaded'), 2000);

  3. list.forEach(item => console.log(item));

10.隐式返回值简写

经常使用return语句来返回函数最终结果,一个单独语句的箭头函数能隐式返回其值(函数必须省略{}为了省略return关键字)

为返回多行语句(例如对象字面表达式),则需要使用()包围函数体。

  1. function calcCircumference(diameter) {

  2.  return Math.PI * diameter

  3. }

  4. var func = function func() {

  5.  return { foo: 1 };

  6. };

简写:

  1. calcCircumference = diameter => (

  2.  Math.PI * diameter;

  3. )

  4. var func = () => ({ foo: 1 });

11.默认参数值

为了给函数中参数传递默认值,通常使用if语句来编写,但是使用ES6定义默认值,则会很简洁:

  1. function volume(l, w, h) {

  2.  if (w === undefined)

  3.    w = 3;

  4.  if (h === undefined)

  5.    h = 4;

  6.  return l * w * h;

  7. }

简写:

  1. volume = (l, w = 3, h = 4 ) => (l * w * h);

  2. volume(2) //output: 24

12.模板字符串

传统的JavaScript语言,输出模板通常是这样写的。

  1. const welcome = 'You have logged in as ' + first + ' ' + last + '.'

  2. const db = 'http://' + host + ':' + port + '/' + database;

ES6可以使用反引号和${}简写:

  1. const welcome = `You have logged in as ${first} ${last}`;

  2. const db = `http://${host}:${port}/${database}`;

13.解构赋值简写方法

在web框架中,经常需要从组件和API之间来回传递数组或对象字面形式的数据,然后需要解构它。

  1. const observable = require('mobx/observable');

  2. const action = require('mobx/action');

  3. const runInAction = require('mobx/runInAction');

  4. const store = this.props.store;

  5. const form = this.props.form;

  6. const loading = this.props.loading;

  7. const errors = this.props.errors;

  8. const entity = this.props.entity;

简写:

  1. import { observable, action, runInAction } from 'mobx';

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

也可以分配变量名:

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

  2. //最后一个变量名为contact

14.多行字符串简写

需要输出多行字符串,需要使用+来拼接:

  1. const lorem = 'Lorem ipsum dolor sit amet, consectetur '

  2.    + 'adipisicing elit, sed do eiusmod tempor incididunt '

  3.    + 'ut labore et dolore magna aliqua. Ut enim ad minim '

  4.    + 'veniam, quis nostrud exercitation ullamco laboris '

  5.    + 'nisi ut aliquip ex ea commodo consequat. Duis aute '

  6.    + 'irure dolor in reprehenderit in voluptate velit esse. '

使用反引号,则可以达到简写作用:

  1. const lorem = `Lorem ipsum dolor sit amet, consectetur

  2.    adipisicing elit, sed do eiusmod tempor incididunt

  3.    ut labore et dolore magna aliqua. Ut enim ad minim

  4.    veniam, quis nostrud exercitation ullamco laboris

  5.    nisi ut aliquip ex ea commodo consequat. Duis aute

  6.    irure dolor in reprehenderit in voluptate velit esse.`

15.扩展运算符简写

扩展运算符有几种用例让JavaScript代码更加有效使用,可以用来代替某个数组函数。

  1. // joining arrays

  2. const odd = [1, 3, 5];

  3. const nums = [2 ,4 , 6].concat(odd);

  4. // cloning arrays

  5. const arr = [1, 2, 3, 4];

  6. const arr2 = arr.slice()

简写:

  1. // joining arrays

  2. const odd = [1, 3, 5 ];

  3. const nums = [2 ,4 , 6, ...odd];

  4. console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]

  5. // cloning arrays

  6. const arr = [1, 2, 3, 4];

  7. const arr2 = [...arr];

不像concat()函数,可以使用扩展运算符来在一个数组中任意处插入另一个数组。

  1. const odd = [1, 3, 5 ];

  2. const nums = [2, ...odd, 4 , 6];

也可以使用扩展运算符解构:

  1. const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };

  2. console.log(a) // 1

  3. console.log(b) // 2

  4. console.log(z) // { c: 3, d: 4 }

16.强制参数简写

JavaScript中如果没有向函数参数传递值,则参数为undefined。为了增强参数赋值,可以使用if语句来抛出异常,或使用强制参数简写方法。

  1. function foo(bar) {

  2.  if(bar === undefined) {

  3.    throw new Error('Missing parameter!');

  4.  }

  5.  return bar;

  6. }

简写:

  1. mandatory = () => {

  2.  throw new Error('Missing parameter!');

  3. }

  4. foo = (bar = mandatory()) => {

  5.  return bar;

  6. }

17.Array.find简写

想从数组中查找某个值,则需要循环。在ES6中,find()函数能实现同样效果。

  1. const pets = [

  2.  { type: 'Dog', name: 'Max'},

  3.  { type: 'Cat', name: 'Karl'},

  4.  { type: 'Dog', name: 'Tommy'},

  5. ]

  6. function findDog(name) {

  7.  for(let i = 0; i<pets.length; ++i) {

  8.    if(pets[i].type === 'Dog' && pets[i].name === name) {

  9.      return pets[i];

  10.    }

  11.  }

  12. }

简写:

  1. pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');

  2. console.log(pet); // { type: 'Dog', name: 'Tommy' }

18.Object[key]简写

考虑一个验证函数:

  1. function validate(values) {

  2.  if(!values.first)

  3.    return false;

  4.  if(!values.last)

  5.    return false;

  6.  return true;

  7. }

  8. console.log(validate({first:'Bruce',last:'Wayne'})); // true

假设当需要不同域和规则来验证,能否编写一个通用函数在运行时确认?

  1. // 对象验证规则

  2. const schema = {

  3.  first: {

  4.    required:true

  5.  },

  6.  last: {

  7.    required:true

  8.  }

  9. }

  10. // 通用验证函数

  11. const validate = (schema, values) => {

  12.  for(field in schema) {

  13.    if(schema[field].required) {

  14.      if(!values[field]) {

  15.        return false;

  16.      }

  17.    }

  18.  }

  19.  return true;

  20. }

  21. console.log(validate(schema, {first:'Bruce'})); // false

  22. console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true

现在可以有适用于各种情况的验证函数,不需要为了每个而编写自定义验证函数了

19.双重非位运算简写

有一个有效用例用于双重非运算操作符。可以用来代替Math.floor(),其优势在于运行更快,可以阅读此文章了解更多位运算。

  1. Math.floor(4.9) === 4  //true

简写:

  1. ~~4.9 === 4  //true

常用的 JavaScript 简写方法的更多相关文章

  1. 19 个常用的 JavaScript 简写方法

    来自:SangSir 链接:https://segmentfault.com/a/1190000012673854 原文:https://www.sitepoint.com/shorthand-jav ...

  2. 【JS】369- 20个常用的JavaScript字符串方法

    点击上方"前端自习课"关注,学习起来~ 作者:前端小智 https://segmentfault.com/a/1190000020204425 本文主要介绍一些最常用的JS字符串函 ...

  3. 20个常用的JavaScript字符串方法

    摘要: 玩转JS字符串. 原文:JS 前20个常用字符串方法及使用方式 译者:前端小智 Fundebug经授权转载,版权归原作者所有. 本文主要介绍一些最常用的JS字符串函数. 1. charAt(x ...

  4. 10 个超棒的 JavaScript 简写技巧

    今天我要分享的是10个超棒的JavaScript简写方法,可以加快开发速度,让你的开发工作事半功倍哦. 开始吧! 1. 合并数组 普通写法: 我们通常使用Array中的concat()方法合并两个数组 ...

  5. 原生JavaScript常用本地浏览器存储方法一(方法类型)

    有时需要将网页中的一些数据保存在浏览器端.好处就是当下次访问页面时,直接就可以从本地读取数据,不需要再次向服务器请求数据.目前常用的有以下几种方法: 1.cookie cookie会随着每次HTTP请 ...

  6. 常用的JavaScript模式

    模式是解决或者避免一些问题的方案. 在JavaScript中,会用到一些常用的编码模式.下面就列出了一些常用的JavaScript编码模式,有的模式是为了解决特定的问题,有的则是帮助我们避免一些Jav ...

  7. GOF提出的23种设计模式是哪些 设计模式有创建形、行为形、结构形三种类别 常用的Javascript中常用设计模式的其中17种 详解设计模式六大原则

    20151218mark 延伸扩展: -设计模式在很多语言PHP.JAVA.C#.C++.JS等都有各自的使用,但原理是相同的,比如JS常用的Javascript设计模式 -详解设计模式六大原则 设计 ...

  8. ES6 模版字符串及常用的es6扩展方法

    1.ES6 模版字符串es6 模版字符串主要用于简化字符串的拼接 <script type="text/javascript"> let obj={name:'rdb' ...

  9. jQuery 的选择器常用的元素查找方法

    jQuery 的选择器常用的元素查找方法 基本选择器: $("#myELement")    选择id值等于myElement的元素,id值不能重复在文档中只能有一个id值是myE ...

随机推荐

  1. [CROATIAN2009] OTOCI

    [题目链接] https://www.lydsy.com/JudgeOnline/problem.php?id=1180 [算法] 动态树维护森林连通性 时间复杂度 : O(NlogN ^ 2) [代 ...

  2. 关于yolo 模型中1X1卷积层的作用

    1X1卷积层的作用: 1.实现跨通道的交互和信息整合.2.进行卷积核通道数的降维和升维.3.就是可以在保持feature map 尺寸不变(即不损失分辨率)的前提下大幅增加非线性特性,把网络做得很de ...

  3. SIM卡(单卡)配置

    SIM卡相关配置 1.GPIO90--->BPI8 GPIO91--->BPI9 GPIO92--->BPI10 2.ProjectConfig.mk:MTK_PROTOCOL1_R ...

  4. 九、myeclipse开发背景保护色设置

    window->preferences->Editors->Text Editors->Background color 背景颜色向你推荐: 色调:85.饱和度:1 2 3.亮 ...

  5. PHP参数类型

    class User{      public $name;      public $password;      function __construct($name,$password){    ...

  6. PICO SCOPE 3000 Series 示波器

  7. 3-3 浮点型字面量 & 3-4浮点型案例

    双精度的浮点类型,末尾加d或者D 3-4浮点型案例 如果一个浮点类型的末尾什么也不写 他表示就是一个double类型的.所以这里定义报错了. float f=1234.328; 把一个范围大的数赋值给 ...

  8. mysql 事务 存储过程 函数

    一:事务: 开启一个事务可以包含一些SQL语句,这些sql语句要么同时成功, 要么一个都别想成功, 称之我事务的原子性 事务用于将某些操作的多个SQL 作为原子性操作, 一旦有某一个出现错误, 即可以 ...

  9. Junit使用注意点

    注意点 1. 使用了@BeforeClass后@Ignore将会失效

  10. [WIP]webpack入门

    创建: 2019/04/09  安装 npm install --save-dev webpack # 最新版 npm install --save-dev webpack@<version&g ...