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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM