美文网首页
常用的 JavaScript 简写方法

常用的 JavaScript 简写方法

作者: iliuqiang | 来源:发表于2020-03-14 09:29 被阅读0次

1、短路求值简写方式

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

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

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

const variable2 = variable1  || 'new';

2、隐式返回值简写

经常使用return语句来返回函数最终结果,一个单独语句的箭头函数能隐式返回其值(函数必须省略{}为了省略return关键字)
为返回多行语句(例如对象字面表达式),则需要使用()包围函数体。

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

var func=function func(){
    return {foo:1};
}

简写:

calcCircumference=diameter=>{
    Math.PI*diameter;
}
var func=()=>({foo:1});

3、默认参数值

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

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

简写:

volume=(1,w=3,h=4)=>(1*w*h);
volume(2)  //output:24;

4、模板字符串

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

const welcome='You have logged in as'+first+last;
const db='http://'+host+':'+port+'/'+database;

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

const welcome = `You have logged in as ${first} &{last}`;
const db=`http://${host}:${port}/${database}`

5、解构赋值简写方法

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

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;

简写:

import {observable,action,runInAction} from 'mbox';
const {store,form,loading,errors,entity}=this.props;

6、扩展运算符简写

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

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

简写:

const odd=[1,3,5];
const nums=[2,4,6,...odd];
console.log(nums); //output:[2, 4, 6, 1, 3, 5]

扩展运算符来可以在一个数组中任意处插入另一个数组:

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}

7、强制参数简写

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

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

简写:

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

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

8、Object[key]简写

考虑一个验证函数:

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

console.log(validate({first:'Tom',last:'Jack'}));  //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:'Tom'})); //false
console.log(validate(schema,{first:'Tom',last:'Jack'}));  //true

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

9、双重非位运算简写

有一个有效用例用于双重非运算操作符。可以用来代替Math.floor(),其优势在于运行更快

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

简写:

~~4.9===4

相关文章

网友评论

      本文标题:常用的 JavaScript 简写方法

      本文链接:https://www.haomeiwen.com/subject/dxcmshtx.html