JavaScript 代码简写技巧

前端之家收集整理的这篇文章主要介绍了JavaScript 代码简写技巧前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

三元表达式

如果你想用一行代码写 if else 语句,不得不想起三元表达式

 10) {
  answer = 'is greater';
} else {
  answer = 'is lesser';
}@H_301_7@

简写

 10 ? 'is greater' : 'is lesser';

or

const big = x > 10 ? "greater 10" : x;@H_301_7@

短路求值

将变量的值赋值给另一个变量时,我们想保证原变量不是 null,undefine 或 '',我们可能会使用很长的 if 条件语句,也可以使用短路求值

or

let dbHost;
if (process.env.DB_HOST) {
dbHost = process.env.DBHOST;
} else {
dbHost = 'localhost';
}
@H301_7@

简写

or

const dbHost = process.env.DB_HOST || 'localhost';

eg

let variable1;
let variable2 = variable1 || '';
console.log(variable2 === ''); // true

variable1 = 'foo';
variable2 = variable1 || '';
console.log(variable2); // foo
@H_301_7@

声明变量

函数头部同时声明多个变量,可以节约大量时间和空间

@H_301_7@

简写

@H_301_7@

if 检查

这可能微不足道,但还是值得提及.在执行 if 检查时,赋值操作符有时可以省略

or

let a;
if ( a !== true ) {
// do something...
}
@H_301_7@

简写

if (likeJavaScript)

or

let a;
if ( !a ) {
// do something...
}
@H_301_7@

for 循环

如果你想用原生 JS,而不依赖类似 jQuery 或 lodash 这样的类库,这个就非常有用

@H_301_7@

简写

@H_301_7@

对 Array.forEach

301_7@

十进制指数

你可能看到过这种写法,它的本质是对数字的一种特殊写法,就像 1e7 等价于 10 000 000

@H_301_7@

简写

// All the below will evaluate to true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;
@H_301_7@

对象属性

当对象某属性名称与值相等时,ES 6 提供了以下简写

@H_301_7@

简写

@H_301_7@

箭头函数

经典函数形式简单,易于阅读和书写,但在嵌套时容易出现代码冗余和混乱

setTimeout(function() {
console.log('Loaded')
},2000);

list.forEach(function(item) {
console.log(item);
});
@H_301_7@

简写

 console.log('Hello',name);

setTimeout(() => console.log('Loaded'),2000);

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

隐式返回

return 是我们经常使用的返回函数最终结果的关键字.箭头函数只有一行语句可以省略 {} 隐式返回结果,如果是多行语句,可以使用 () 代替 {} 返回多行语句

@H_301_7@

简写

 (
  Math.PI * diameter;
)@H_301_7@

默认参数值

你可以使用 if 语句来定义函数参数的默认值,在 ES 6 中,可以在函数声明中定义默认值

or

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

简写

 (l * w * h);
volume(2); // 24

or

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

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

模板字符串

你厌倦了使用 + 来连接多个变量拼凑成字符串吗,ES 6 可以使用模板字符串即 `` 和 ${} 来拼凑你的字符串,并且它可以更好地书写多行字符串

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

# or

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'@H_301_7@

    简写

    
    

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

or

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.@H_301_7@

解构赋值

如果你正在使用目前流行的 web 框架,那么就极有可能会将值从数组或将属性从对象提取到不同的变量中,比如加载一个模块的特定子集

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;
@H_301_7@

简写

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

扩展运算符

ES 6 中引入的扩展运算符让 javascript 代码更加高效和有趣,他可以用来替代某些数组的功能

// cloning arrays
const arr = [1,2,4];
const arr2 = arr.slice()
@H_301_7@

简写

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

与解构符结合使用

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 }
@H_301_7@

Array.find

如果你使用原生 JS 实现查找,那么你会用到 for 循环.在 ES 6 中,我们可以使用新引进的 find

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

简写

 pet.type === 'Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog',name: 'Tommy' }@H_301_7@

Object [key]

你知道 Foo.bar 也可以写成 Foo['bar'] 吗,似乎没有理由该这样写,然而这种书写方式可以使代码复用性更高

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

简写

// 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
@H_301_7@

~~ 运算符

~~ 可以替代 Math.floor(),并且它更快

@H_301_7@

简写

@H_301_7@

猜你在找的JavaScript相关文章