javascript一些新的特性整理(2)

10.省略return的隐式返回。

Return是我们经常使用的关键字,用于返回函数的最终结果。具有单个语句的箭头函数将隐式返回其评估结果(函数必须省略大括号{}以省略return关键字)
要返回多行语句(例如字符串对象),必须使用()而不是{}来包住你的函数体。这可确保将代码看成为单个语句计算。

bad code

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

good code

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

11.默认参数值

可以使用if语句定义函数参数的默认值。在ES6中,我们可以在函数声明本身中定义默认值。

bad code

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

good code

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

volume(2) //output: 24

12.模板文字

您是否厌倦了使用’+’多个变量连接成一个字符串?这样做有没有更简单的方法?使用反引号,并包含您的变量。${}

bad code

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

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

good code

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

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

13. 解构赋值

如果您正在使用任何流行的Web框架,那么很有可能您将使用字符串对象形式的数组或数据在组件和API之间传递信息。一旦数据对象到达组件,您将需要解压缩它。

bad code

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;

good code

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

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

你也可以指派自己的变量名

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

14.多行字符串短的写法

bad code

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

good code

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.`

15 …扩展运算符快速写法

bad code

// 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()

good code

//joining arrays
const odd = [1,3,5];
const nums = [2, 4, 6, ...odd]; # 类似python的*args
console.log(nums);

//cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];

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

const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a) // 1
console.log(b) // 2
console.log(z) // { c: 3, d: 4 }

16.强制参数写法

bad code

function foo(bar) {
  if(bar === undefined) {
    throw new Error('Missing parameter!');
  }
  return bar;
}

good code

mandatory = () => {
  throw new Error('Missing parameter!');
}

foo = (bar = mandatory()) => {
  return bar;
}

17.数组查找

如果在es6之前,查找使用的还是for循环遍历的方式,那么现在,已经可以使用ES6里面的find()了。

bad code

const pets = [
  { type: 'Dog', name: 'Max'},
  { type: 'Cat', name: 'Karl'},
  { type: 'Dog', name: 'Tommy'},
]

function findDog(name) {
  for(let i = 0; i<pets.length; ++i) {
    if(pets[i].type === 'Dog' && pets[i].name === name) {
      return pets[i];
    }
  }
}

good code

pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }

18.object[key]的写法

foo.bar 其实还可以写成 foo[‘bar’]

bad code

function validate(values) {
  if(!values.first)
    return false;
  if(!values.last)
    return false;
  return true;
}

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

此功能完美地完成了它的工作。但是,请考虑这样一种情况,即您需要应用验证但具有不同字段和规则的表单非常多。构建可在运行时配置的通用验证函数不是很好吗?

good code

// object validation rules
const schema = {
  first: {
    required:true
  },
  last: {
    required:true
  }
}

// universal validation function
const validate = (schema, values) => {
  for(field in schema) {
    if(schema[field].required) {
      if(!values[field]) {
        return false;
      }
    }
  }
  return true;
}


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

现在我们有一个验证函数,我们可以在所有表​​单中重用,而无需为每个表单编写自定义验证函数。

19. 按位操作符

Double Bitwise NOT运算符有一个非常实用的用例.Double Bitwise NOT运算符的优点是它可以更快地执行相同的操作

按位非操作符由一个波浪线(~)表示,执行按位非的结果就是返回数值的反码。按位非是 ECMAScript 操作符中少数几个与二进制计算有关的操作符之一。

还可以用两次按位非(NOT)做高效的取整,详见 James Padolsey 的文章 Double bitwise NOT(~~)
http://james.padolsey.com/javascript/double-bitwise-not/

long

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

short

~~4.9 === 4  //true

猜你喜欢

转载自blog.csdn.net/funnyPython/article/details/81487511