Table of Contents
This article mainly shares 19 useful JavaScript abbreviation techniques with you, hoping to help everyone. " >This article mainly shares 19 useful JavaScript abbreviation techniques with you, hoping to help everyone.
1. Ternary operator" >1. Ternary operator
2. Short-circuit evaluation abbreviation " >2. Short-circuit evaluation abbreviation
3. Abbreviated method of declaring variables " >3. Abbreviated method of declaring variables
4.if exists condition abbreviation method" >4.if exists condition abbreviation method
" >6. Short-circuit evaluation
" >7. Decimal exponent
" > 8. Object attribute abbreviation
" >9. Arrow function abbreviation
13.解构赋值简写方法" >13.解构赋值简写方法
14.多行字符串简写" >14.多行字符串简写
15.扩展运算符简写" >15.扩展运算符简写
16.强制参数简写" >16.强制参数简写
17.Array.find简写" >17.Array.find简写
18.Object[key]简写" >18.Object[key]简写
19.双重非位运算简写" >19.双重非位运算简写
Home Web Front-end JS Tutorial 19 useful shorthand techniques for JavaScript

19 useful shorthand techniques for JavaScript

Jan 03, 2018 pm 02:56 PM
javascript js share

This article mainly shares 19 useful JavaScript abbreviation techniques with you, hoping to help everyone.

1. Ternary operator

When you want to write an if...else statement, use the ternary operator instead.

1

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

Copy after login

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

You can also nest if statements:
<span style="font-size: 16px;">const big = x > 10 ? " greater 10" : x</span>

2. Short-circuit evaluation abbreviation

When assigning another value to a variable, you want to make sure that the original value is not null, undefined or empty. You can write a multi-condition if statement.

1

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

Copy after login

Or you can use the short-circuit evaluation method:
<span style="font-size: 16px;">const variable2 = variable1 || 'new';</span>

3. Abbreviated method of declaring variables

1

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

Copy after login

Abbreviated method:
<span style="font-size: 16px;">let x, y, z=3 ;</span>

4.if exists condition abbreviation method

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

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

only when likeJavaScript is true , the two statements are equal

If the judgment value is not a true value, you can do this:

1

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

Copy after login

Abbreviation:

1

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

Copy after login

5. JavaScript loop abbreviation method

for (let i = 0; i < allImgs.length; i++)<span style="font-size: 16px;"></span>

Abbreviation:
for (let index in allImgs)<span style="font-size: 16px;"></span>
You can also use Array.forEach:

1

<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>

Copy after login

6. Short-circuit evaluation

The value assigned to a variable is determined by judging whether the value is null or undefined, then you can:

1

<span style="font-size: 16px;">let dbHost;<br/>if (process.env.DB_HOST) {<br/>  dbHost = process.env.DB_HOST;<br/>} else {<br/>  dbHost = &#39;localhost&#39;;<br/>}<br/></span>

Copy after login

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

7. Decimal exponent

When you need to write a number with many zeros (such as 10000000), you can use the exponent (1e7) to replace this number:
for (let i = 0; i < 10000; i++) {}<span style="font-size: 16px;"></span>
Abbreviation:

1

<span style="font-size: 16px;">for (let i = 0; i < 1e7; i++) {}<br/><br/>// 下面都是返回true<br/>1e0 === 1;<br/>1e1 === 10;<br/>1e2 === 100;<br/>1e3 === 1000;<br/>1e4 === 10000;<br/>1e5 === 100000;<br/></span>

Copy after login

8. Object attribute abbreviation

If the attribute name is the same as the key name, you can use the ES6 method:
const obj = { x: x, y:y };<span style="font-size: 16px;"></span>

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

9. Arrow function abbreviation

The traditional function writing method is easy for people to understand and write, but when nested in another function, then These advantages are gone.

1

<span style="font-size: 16px;">function sayHello(name) {<br/>  console.log(&#39;Hello&#39;, name);<br/>}<br/><br/>setTimeout(function() {<br/>  console.log(&#39;Loaded&#39;)<br/>}, 2000);<br/><br/>list.forEach(function(item) {<br/>  console.log(item);<br/>});<br/></span>

Copy after login

Abbreviation:

1

2

3

4

5

6

<span style="font-size: 16px;">sayHello = name => console.log('Hello', name);<br><br>setTimeout(() => console.log('Loaded'), 2000);<br><br>list.forEach(item => console.log(item));<br></code></p>

<h2>10. Implicit return value abbreviation<span style="font-size: 16px;"></span>

</h2>

<p>Return is often used statement to return the final result of a function, an arrow function with a single statement can implicitly return its value (the function must omit {} in order to omit the return keyword) <span style="font-size: 16px;"></span></p>

<p> is a statement that returns multiple lines (for example Object literal expression), you need to surround the function body with (). <span style="font-size: 16px;"></span></p>

<pre class="brush:php;toolbar:false"><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>

Copy after login

Abbreviation:

1

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

Copy after login

11.Default parameter value

In order to provide parameters in the function Passing default values ​​is usually written using if statements, but using ES6 to define default values ​​will be very concise:

1

<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>

Copy after login

Abbreviation:

1

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

Copy after login

12. Template string

In traditional JavaScript language, the output template is usually written like this.

1

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

Copy after login

ES6 can use backticks and ${} abbreviation:

1

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

Copy after login

13.解构赋值简写方法

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

1

<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>

Copy after login

简写:

1

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

Copy after login

也可以分配变量名:

1

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

Copy after login

14.多行字符串简写

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

1

<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>

Copy after login

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

1

<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>

Copy after login

15.扩展运算符简写

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

1

<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>

Copy after login

简写:

1

<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>

Copy after login

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

1

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

Copy after login

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

1

<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>

Copy after login

16.强制参数简写

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

1

<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>

Copy after login

简写:

1

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

Copy after login

17.Array.find简写

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

1

<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; ++i) {<br/>    if(pets[i].type === &#39;Dog&#39; && pets[i].name === name) {<br/>      return pets[i];<br/>    }<br/>  }<br/>}<br/></span>

Copy after login

简写:

1

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

Copy after login

18.Object[key]简写

考虑一个验证函数

1

<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>

Copy after login

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

1

<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) => {<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>

Copy after login

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

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 中的三元运算符

The above is the detailed content of 19 useful shorthand techniques for JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to share Quark Netdisk to Baidu Netdisk? How to share Quark Netdisk to Baidu Netdisk? Mar 14, 2024 pm 04:40 PM

Quark Netdisk and Baidu Netdisk are very convenient storage tools. Many users are asking whether these two softwares are interoperable? How to share Quark Netdisk to Baidu Netdisk? Let this site introduce to users in detail how to save Quark network disk files to Baidu network disk. How to save files from Quark Network Disk to Baidu Network Disk Method 1. If you want to know how to transfer files from Quark Network Disk to Baidu Network Disk, first download the files that need to be saved on Quark Network Disk, and then open the Baidu Network Disk client. , select the folder where the compressed file is to be saved, and double-click to open the folder. 2. After opening the folder, click "Upload" in the upper left corner of the window. 3. Find the compressed file that needs to be uploaded on your computer and click to select it.

How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments Mar 25, 2024 am 11:41 AM

1. First, we enter NetEase Cloud Music, and then click on the software homepage interface to enter the song playback interface. 2. Then in the song playback interface, find the sharing function button in the upper right corner, as shown in the red box in the figure below, click to select the sharing channel; in the sharing channel, click the &quot;Share to&quot; option at the bottom, and then select the first &quot;WeChat Moments&quot; allows you to share content to WeChat Moments.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to share files with friends on Baidu Netdisk How to share files with friends on Baidu Netdisk Mar 25, 2024 pm 06:52 PM

Recently, Baidu Netdisk Android client has ushered in a new version 8.0.0. This version not only brings many changes, but also adds many practical functions. Among them, the most eye-catching is the enhancement of the folder sharing function. Now, users can easily invite friends to join and share important files in work and life, achieving more convenient collaboration and sharing. So how do you share the files you need to share with your friends? Below, the editor of this site will give you a detailed introduction. I hope it can help you! 1) Open Baidu Cloud APP, first click to select the relevant folder on the homepage, and then click the [...] icon in the upper right corner of the interface; (as shown below) 2) Then click [+] in the &quot;Shared Members&quot; column 】, and finally check all

Mango tv member account sharing 2023 Mango tv member account sharing 2023 Feb 07, 2024 pm 02:27 PM

Mango TV has various types of movies, TV series, variety shows and other resources, and users can freely choose to watch them. Mango TV members can not only watch all VIP dramas, but also set the highest definition picture quality to help users watch dramas happily. Below, the editor will bring you some free Mango TV membership accounts for users to use, hurry up and take a look Take a look. Mango TV latest member account free sharing 2023: Note: These are the latest member accounts collected, you can log in directly and use them, do not change the password at will. Account number: 13842025699 Password: qds373 Account number: 15804882888 Password: evr6982 Account number: 13330925667 Password: jgqae Account number: 1703

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Solve the problem that Discuz WeChat sharing cannot be displayed Solve the problem that Discuz WeChat sharing cannot be displayed Mar 09, 2024 pm 03:39 PM

Title: To solve the problem that Discuz WeChat shares cannot be displayed, specific code examples are needed. With the development of the mobile Internet, WeChat has become an indispensable part of people's daily lives. In website development, in order to improve user experience and expand website exposure, many websites will integrate WeChat sharing functions, allowing users to easily share website content to Moments or WeChat groups. However, sometimes when using open source forum systems such as Discuz, you will encounter the problem that WeChat shares cannot be displayed, which brings certain difficulties to the user experience.

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

See all articles