19 个 JavaScript 常用的简写技术
1.三元操作符
const x = 20;let answer;if (x > 10) { answer = 'is greater';} else { answer = 'is lesser';}
const answer = x > 10 ? 'is greater' : 'is lesser';
const big = x > 10 ? " greater 10" : x2.短路求值简写方式
if (variable1 !== null || variable1 !== undefined || variable1 !== '') { let variable2 = variable1;}
const variable2 = variable1 || 'new';3.声明变量简写方法let x;let y;let z = 3;
let x, y, z=3;4.if存在条件简写方法if (likeJavaScript === true)
if (likeJavaScript)
只有likeJavaScript是真值时,二者语句才相等
let a;if ( a !== true ) {// do something...}
let a;if ( !a ) {// do something...}5.JavaScript循环简写方法for (let i = 0; i < allImgs.length; i++)
for (let index in allImgs)
function logArrayElements(element, index, array) { console.log("a[" + index + "] = " + element);}[2, 5, 9].forEach(logArrayElements);// logs:// a[0] = 2// a[1] = 5// a[2] = 96.短路评价
let dbHost;if (process.env.DB_HOST) { dbHost = process.env.DB_HOST;} else { dbHost = 'localhost';}
const dbHost = process.env.DB_HOST || 'localhost';7.十进制指数
for (let i = 0; i < 10000; i++) {}
for (let i = 0; i < 1e7; i++) {}// 下面都是返回true1e0 === 1;1e1 === 10;1e2 === 100;1e3 === 1000;1e4 === 10000;1e5 === 100000;8.对象属性简写
const obj = { x:x, y:y };
const obj = { x, y };9.箭头函数简写
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));10.隐式返回值简写
function calcCircumference(diameter) { return Math.PI * diameter}var func = function func() { return { foo: 1 };};
calcCircumference = diameter => ( Math.PI * diameter;)var func = () => ({ foo: 1 });11.默认参数值
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: 2412.模板字符串
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}`;13.解构赋值简写方法
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;//最后一个变量名为contact14.多行字符串简写
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. '
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.扩展运算符简写
// joining arraysconst odd = [1, 3, 5];const nums = [2 ,4 , 6].concat(odd);// cloning arraysconst arr = [1, 2, 3, 4];const arr2 = arr.slice()
// joining arraysconst odd = [1, 3, 5 ];const nums = [2 ,4 , 6, ...odd];console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]// cloning arraysconst 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) // 1console.log(b) // 2console.log(z) // { c: 3, d: 4 }16.强制参数简写
function foo(bar) { if(bar === undefined) { throw new Error('Missing parameter!'); } return bar;}
mandatory = () => { throw new Error('Missing parameter!');}foo = (bar = mandatory()) => { return bar;}17.Array.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.type === 'Dog' && pets.name === name) { return pets; } }}
pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');console.log(pet); // { type: 'Dog', name: 'Tommy' }18.Object[key]简写
function validate(values) { if(!values.first) return false; if(!values.last) return false; return true;}console.log(validate({first:'Bruce',last:'Wayne'})); // true
// 对象验证规则const schema = { first: { required:true }, last: { required:true }}// 通用验证函数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'})); // falseconsole.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true
浙公网安备 33010602011771号