js代码简化(含es6)

1 for-of loop(for循环)

 for (let i = 0; i < .length; i++)
//简化为
for (let index of allImgs)
//用于循环key,不推荐在数组使用
for (let index in allImgs)

var arr = ['a', 'b', 'c'];
arr.forEach(function (elem, index) {
    console.log('index = '+index+', elem = '+elem);
});

es6写法:

    const arr = ['a', 'b', 'c'];
    for(const [index,value] of arr.entries() ) {
        console.log('index = ${index}, elem = ${elem}');
}

备注:.entries(),数组对象方法,返回一个迭代器

var entries = ["a", "b", "c"].entries();
// entries.next().value == [0, "a"]
// entries.next().value == [1, "b"]
// entries.next().value == [2, "c"] 

2 ....扩展运算符

// 合并
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);

// 克隆
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()
// es6简写
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]


const arr1 = ['a','b','c'];
const arr2 = [1,...arr1,3];
=>
arr2 = [1,'a','b','c',3];

扩展运算符相当于把内容全部展开

3 短路求值

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

4 十进制指数
可能你早就知道了,这是一个不用在末尾写一堆0的方法。例如1e7代表1后面跟7个0,也就是十进制的1000000。

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

1e0 === 1; //true
1e1 === 10; //true
1e2 === 100; //true
1e3 === 1000; //true

5 对象属性的缩写
es6,如果属性名和值一样的话,你可以如下缩写

const obj = { x:x, y:y };
// 等同于
const obj = { x, y };

在vue中大量使用 如

new Vue({
    el: '#app',
    data: {
    userinfo
    },
    router,
    store,
    render: (h) => h(App)
});

6 箭头函数

function sayHi(name) {
  console.log('Hi', name);
}

setTimeout(function() {
  console.log('666')
}, 1000);

list.forEach(function(item) {
  console.log(item);
});
// es6箭头函数,需注意箭头函数里的this指向上下文this,与普通函数不同(谁调用指向谁)
sayHi = name => console.log('Hi', name);

setTimeout(() => console.log('666'), 1000);

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

箭头函数的隐形return(必须为一行语句)

function calcCircumference(diameter) {
  return Math.PI * diameter
}
简写  =>
calcCircumference = diameter => Math.PI * diameter

7 默认参数
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
--------------------------------------------------
例子:
 function err () {
 throw new Error ("Error:have no Parameter");
}
function foo(mustBeProvided = err()) {
    return mustBeProvided;
}
--------------------------------------------------
    foo()
=>  Error:have no Parameter
    foo(123)
=>  123

8 反引号与模板字符串
const hello = 'welcome to zhuhai ,' + name + '!';

const url = 'http://' + host + ':' + port + '/' + database;
// 简化为
const welcome = `welcome to zhuhai , ${name}`;

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

9 解构赋值

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;

10 反引号与多行字符串

JavaScriptconst 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'
// 简化为
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.`

11 Array.find
用for循环写过一个find函数

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];
}
  }
}
// ES6新特性(Array.find)
pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }

12.函数参数解构

function fn({x, y} = {x:0,y:0}) {
   return [x, y];
}
console.log(fn({x: 1, y: 2}));// [1, 2]
console.log(fn({x: 1}));// [1, undefined]
console.log(fn({}));// [undefined, undefined]
console.log(fn());// [0, 0]  无实参传递进来,对{x:0,y:0}解构

箭头函数可以与变量解构结合使用

const full = ({ first, last }) => first + ' ' + last;

// 等同于
function full(person) {
  return person.first + ' ' + person.last;
}

项目中常用在函数调用(http请求)后参数解构

XX.checkLogin().done(({value}) => {
    new Vue({
        el: '#app',
        data: {
            userinfo: value
        },
        router,
        store,
        render: (h) => h(App)
    });
});

更多参考http://es6.ruanyifeng.com/#docs/destructuring

转载于:https://www.cnblogs.com/shenkangfei/p/7600943.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值