登录  /  注册
首页 > web前端 > js教程 > 正文

19 个 JavaScript 有用的简写技术分享

小云云
发布: 2018-01-03 14:56:52
原创
2867人浏览过

本文主要和大家分享19 个 JavaScript 有用的简写技术,希望能帮助到大家。

1.三元操作符

当想写if...else语句时,使用三元操作符来代替。

<span style="font-size: 16px;">const x = 20;<br>let answer;<br>if (x &gt; 10) {<br>    answer = 'is greater';<br>} else {<br>    answer = 'is lesser';<br>}<br></span>
登录后复制

简写:
<span style="font-size: 16px;">const answer = x &gt; 10 ? 'is greater' : 'is lesser';</span>

也可以嵌套if语句:
<span style="font-size: 16px;">const big = x &gt; 10 ? " greater 10" : x</span>

2.短路求值简写方式

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

<span style="font-size: 16px;">if (variable1 !== null || variable1 !== undefined || variable1 !== '') {<br>     let variable2 = variable1;<br>}<br></span>
登录后复制

或者可以使用短路求值方法:
<span style="font-size: 16px;">const variable2 = variable1  || 'new';</span>

3.声明变量简写方法

<span style="font-size: 16px;">let x;<br>let y;<br>let z = 3;<br></span>
登录后复制

简写方法:
<span style="font-size: 16px;">let x, y, z=3;</span>

4.if存在条件简写方法

<span style="font-size: 16px;">if (likeJavaScript === true)</span>

简写:
<span style="font-size: 16px;">if (likeJavaScript)</span>

只有likeJavaScript是真值时,二者语句才相等

如果判断值不是真值,则可以这样:

<span style="font-size: 16px;">let a;<br>if ( a !== true ) {<br>// do something...<br>}<br></span>
登录后复制

简写:

<span style="font-size: 16px;">let a;<br>if ( !a ) {<br>// do something...<br>}<br></span>
登录后复制

5.JavaScript循环简写方法

<span style="font-size: 16px;">for (let i = 0; i </span>

简写:
<span style="font-size: 16px;">for (let index in allImgs)</span>
也可以使用Array.forEach:

<span style="font-size: 16px;">function logArrayElements(element, index, array) {<br>  console.log("a[" + index + "] = " + element);<br>}<br>[2, 5, 9].forEach(logArrayElements);<br>// logs:<br>// a[0] = 2<br>// a[1] = 5<br>// a[2] = 9<br></span>
登录后复制

6.短路评价

给一个变量分配的值是通过判断其值是否为null或undefined,则可以:

<span style="font-size: 16px;">let dbHost;<br>if (process.env.DB_HOST) {<br>  dbHost = process.env.DB_HOST;<br>} else {<br>  dbHost = 'localhost';<br>}<br></span>
登录后复制

简写:
<span style="font-size: 16px;">const dbHost = process.env.DB_HOST || 'localhost';</span>

7.十进制指数

当需要写数字带有很多零时(如10000000),可以采用指数(1e7)来代替这个数字:
<span style="font-size: 16px;">for (let i = 0; i </span>
简写:

<span style="font-size: 16px;">for (let i = 0; i <br>// 下面都是返回true<br>1e0 === 1;<br>1e1 === 10;<br>1e2 === 100;<br>1e3 === 1000;<br>1e4 === 10000;<br>1e5 === 100000;<br></span>
登录后复制

8.对象属性简写

如果属性名与key名相同,则可以采用ES6的方法:
<span style="font-size: 16px;">const obj = { x:x, y:y };</span>

简写:
<span style="font-size: 16px;">const obj = { x, y };</span>

9.箭头函数简写

传统函数编写方法很容易让人理解和编写,但是当嵌套在另一个函数中,则这些优势就荡然无存。

<span style="font-size: 16px;">function sayHello(name) {<br>  console.log('Hello', name);<br>}<br><br>setTimeout(function() {<br>  console.log('Loaded')<br>}, 2000);<br><br>list.forEach(function(item) {<br>  console.log(item);<br>});<br></span>
登录后复制

简写:

<span style="font-size: 16px;">sayHello = name =&gt; console.log('Hello', name);<br><br>setTimeout(() =&gt; console.log('Loaded'), 2000);<br><br>list.forEach(item =&gt; console.log(item));<br></span>
登录后复制

10.隐式返回值简写

经常使用return语句来返回函数最终结果,一个单独语句的箭头函数能隐式返回其值(函数必须省略{}为了省略return关键字)

为返回多行语句(例如对象字面表达式),则需要使用()包围函数体。

<span style="font-size: 16px;">function calcCircumference(diameter) {<br>  return Math.PI * diameter<br>}<br><br>var func = function func() {<br>  return { foo: 1 };<br>};<br></span>
登录后复制

简写:

<span style="font-size: 16px;">calcCircumference = diameter =&gt; (<br>  Math.PI * diameter;<br>)<br><br>var func = () =&gt; ({ foo: 1 });<br></span>
登录后复制

11.默认参数值

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

<span style="font-size: 16px;">function volume(l, w, h) {<br>  if (w === undefined)<br>    w = 3;<br>  if (h === undefined)<br>    h = 4;<br>  return l * w * h;<br>}<br></span>
登录后复制

简写:

<span style="font-size: 16px;">volume = (l, w = 3, h = 4 ) =&gt; (l * w * h);<br><br>volume(2) //output: 24<br></span>
登录后复制

12.模板字符串

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

<span style="font-size: 16px;">const welcome = 'You have logged in as ' + first + ' ' + last + '.'<br><br>const db = 'http://' + host + ':' + port + '/' + database;<br></span>
登录后复制

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

<span style="font-size: 16px;">const welcome = `You have logged in as ${first} ${last}`;<br><br>const db = `http://${host}:${port}/${database}`;<br></span>
登录后复制

13.解构赋值简写方法

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

<span style="font-size: 16px;">const observable = require('mobx/observable');<br>const action = require('mobx/action');<br>const runInAction = require('mobx/runInAction');<br><br>const store = this.props.store;<br>const form = this.props.form;<br>const loading = this.props.loading;<br>const errors = this.props.errors;<br>const entity = this.props.entity;<br></span>
登录后复制

简写:

<span style="font-size: 16px;">import { observable, action, runInAction } from 'mobx';<br><br>const { store, form, loading, errors, entity } = this.props;<br></span>
登录后复制

也可以分配变量名:

<span style="font-size: 16px;">const { store, form, loading, errors, entity:contact } = this.props;<br>//最后一个变量名为contact<br></span>
登录后复制

14.多行字符串简写

需要输出多行字符串,需要使用+来拼接:

<span style="font-size: 16px;">const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t'<br>    + 'adipisicing elit, sed do eiusmod tempor incididunt\n\t'<br>    + 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t'<br>    + 'veniam, quis nostrud exercitation ullamco laboris\n\t'<br>    + 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t'<br>    + 'irure dolor in reprehenderit in voluptate velit esse.\n\t'<br></span>
登录后复制

使用反引号,则可以达到简写作用:

<span style="font-size: 16px;">const lorem = `Lorem ipsum dolor sit amet, consectetur<br>    adipisicing elit, sed do eiusmod tempor incididunt<br>    ut labore et dolore magna aliqua. Ut enim ad minim<br>    veniam, quis nostrud exercitation ullamco laboris<br>    nisi ut aliquip ex ea commodo consequat. Duis aute<br>    irure dolor in reprehenderit in voluptate velit esse.`<br></span>
登录后复制

15.扩展运算符简写

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

<span style="font-size: 16px;">// joining arrays<br>const odd = [1, 3, 5];<br>const nums = [2 ,4 , 6].concat(odd);<br><br>// cloning arrays<br>const arr = [1, 2, 3, 4];<br>const arr2 = arr.slice()<br></span>
登录后复制

简写:

<span style="font-size: 16px;">// joining arrays<br>const odd = [1, 3, 5 ];<br>const nums = [2 ,4 , 6, ...odd];<br>console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]<br><br>// cloning arrays<br>const arr = [1, 2, 3, 4];<br>const arr2 = [...arr];<br></span>
登录后复制

不像concat()函数,可以使用扩展运算符来在一个数组中任意处插入另一个数组。

<span style="font-size: 16px;">const odd = [1, 3, 5 ];<br>const nums = [2, ...odd, 4 , 6];<br></span>
登录后复制

也可以使用扩展运算符解构:

<span style="font-size: 16px;">const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };<br>console.log(a) // 1<br>console.log(b) // 2<br>console.log(z) // { c: 3, d: 4 }<br></span>
登录后复制

16.强制参数简写

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

<span style="font-size: 16px;">function foo(bar) {<br>  if(bar === undefined) {<br>    throw new Error('Missing parameter!');<br>  }<br>  return bar;<br>}<br></span>
登录后复制

简写:

<span style="font-size: 16px;">mandatory = () =&gt; {<br>  throw new Error('Missing parameter!');<br>}<br><br>foo = (bar = mandatory()) =&gt; {<br>  return bar;<br>}<br></span>
登录后复制

17.Array.find简写

想从数组中查找某个值,则需要循环。在ES6中,find()函数能实现同样效果。

<span style="font-size: 16px;">const pets = [<br>  { type: 'Dog', name: 'Max'},<br>  { type: 'Cat', name: 'Karl'},<br>  { type: 'Dog', name: 'Tommy'},<br>]<br><br>function findDog(name) {<br>  for(let i = 0; i<pets.length></pets.length>    if(pets[i].type === 'Dog' &amp;&amp; pets[i].name === name) {<br>      return pets[i];<br>    }<br>  }<br>}<br></span>
登录后复制

简写:

<span style="font-size: 16px;">pet = pets.find(pet =&gt; pet.type ==='Dog' &amp;&amp; pet.name === 'Tommy');<br>console.log(pet); // { type: 'Dog', name: 'Tommy' }<br></span>
登录后复制

18.Object[key]简写

考虑一个验证函数

<span style="font-size: 16px;">function validate(values) {<br>  if(!values.first)<br>    return false;<br>  if(!values.last)<br>    return false;<br>  return true;<br>}<br><br>console.log(validate({first:'Bruce',last:'Wayne'})); // true<br></span>
登录后复制

假设当需要不同域和规则来验证,能否编写一个通用函数在运行时确认?

<span style="font-size: 16px;">// 对象验证规则<br>const schema = {<br>  first: {<br>    required:true<br>  },<br>  last: {<br>    required:true<br>  }<br>}<br><br>// 通用验证函数<br>const validate = (schema, values) =&gt; {<br>  for(field in schema) {<br>    if(schema[field].required) {<br>      if(!values[field]) {<br>        return false;<br>      }<br>    }<br>  }<br>  return true;<br>}<br><br><br>console.log(validate(schema, {first:'Bruce'})); // false<br>console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true<br></span>
登录后复制

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

19.双重非位运算简写

有一个有效用例用于双重非运算操作符。可以用来代替Math.floor(),其优势在于运行更快,可以阅读此文章了解更多位运算。
<span style="font-size: 16px;">Math.floor(4.9) === 4  //true</span>

简写:
<span style="font-size: 16px;">~~4.9 === 4  //true</span>

相关推荐:

js判断是否为空字符串的简写方法实例详解

js的简写写法介绍

怎么简写php 中的三元运算符

以上就是19 个 JavaScript 有用的简写技术分享的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号