Home Web Front-end JS Tutorial Some effective JS tips

Some effective JS tips

Mar 20, 2018 pm 01:37 PM

This article mainly talks about some effective JS tips with you. Friends in need can refer to it. I hope it can help everyone.

1. Ternary operator

When you want to write an if...else statement in the project, if it is not a multiple judgment, You can consider ternary operations instead

let a = 1, answer = null
if( a > 5 ) {
    answer = '大帅比'
}else{ 
    answer = '前端强无敌'
}
简写:answer = a > 5 ?  '大帅比' : '前端强无敌'
Copy after login

2, for simplification (new method provided by ES6)

for(let i = 0; i < arr.length; i++){}
简写:for (let [index, item] of arr.entries()) {
        index为下标,item为每一项内容
}
Copy after login

3, arrow function (es6)

function test (){ console.info(name) }
setTimeout(function() { console.info(&#39;&#39;okay) }, 1500)
arr.forEach(function (item) {    
    console.info(item)
})
简写: let test = (args) => {  console.info(name) }
setTimeout(() => { console.info(&#39;okay&#39;) }, 1500)
arr.forEach(item => console.info(item))
Copy after login

It seems more convenient, this will not change when the arrow function is used~!

4. Extension operator

Array merging:

const a = [1, 3, 5]
const nums = [2, 4, 6].concat(a);
Copy after login

Array cloning: //Because the array is a reference type, it is often necessary to clone a separate one The operation

const arr = [1, 2, 3, 4]
cons arr2 = arr.slice()
简写: const nums = [2, 4, 6,  ...a]  // [2, 4, ...a, 6]
Copy after login

a can be inserted at any position instead of appending only at the end, which is more convenient than concat!

Used in objects:

const obj =  { a:1 , b:2, c:3,  ...obj2 } =  { a:1 , b:2, c:3,  d:5, e: 6}
obje = {d:5, e: 6}
Copy after login

5. Object attribute abbreviation

When the key value is the same

const obj = {x:x,y:y}
简写:cont obj = {x,y}
Copy after login

6. The abbreviation of the line string

const learn = &#39;study vue react rn nih\n\t&#39;
                     +  &#39;study vue react rn nih\n\t&#39;
                     +  &#39;study vue react rn nih\n\t&#39;
                     +  &#39;study vue react rn nih\n\t&#39;
                     +  &#39;study vue react rn nih\n\t&#39;
简写:const learn = `study vue react rn nih
                                  study vue react rn nih
                                 study vue react rn nih
                                 study vue react rn nih
                                study vue react rn nih`
Copy after login

7. The template string

const url = &#39;http://ab.cc.com/&#39; + data + &#39;/beta/info&#39;
简写:const url = `http://ab.cc.com/${data}/beta/info`
Copy after login

${} can be directly put into the variable, which is very easy to use. Easy~remember the backticks! ! !

8. Array.find

If you want to find the required data in an array, you need to loop through it. Find in ES6 can simplify its operation

cont data = [
{&#39;type&#39;: &#39;dog&#39;,  &#39;color&#39;: &#39;red&#39;},
{&#39;type&#39;: &#39;cat&#39;, &#39;color: &#39;white&#39;},
{&#39;type&#39;: &#39;bird&#39;, &#39;color&#39;: &#39;blue&#39;}
]
function findeClor(color) {
        for(let i = 0; i < data.length; i ++ ) {
                if(data[i].type== &#39;cat&#39; && data[i].color== color) {
                        return data[i]
                } 
        }
}
简写:let cat = data.find(item => item.type == &#39;cat&#39; && item.color== &#39;red&#39;)
Copy after login

9. Convert pseudo array to real array (Pseudo array has no interator interface)

let p = document.getElementById(&#39;p&#39;)
Copy after login

p is a pseudo array and cannot be traversed using methods such as forEach. You can use the more troublesome for loop

let p = Array.from(p)  或者 let p = [...p]
Copy after login

At this time, p is a truly traversable array

10. Array deduplication, Set

let a = [2, 3, 1, 2]

new Set() returns a pseudo array. You need to use the spread operator to convert it into a real array. Array.from() is also good. Selection

let b = [... new Set(a)] // [2, 3, 1]

11. Default parameters

function test(a, b, c = 'Dashuaibi', d = false){

}

test('front-end', 'Beima')

If the two parameters c and d are not passed in, then c defaults to 'Dashuaibi' and d defaults to false

12. Mandatory parameters

JS , if the function does not pass parameters, the parameters will default to undefined. This may cause a program exception, and an exception needs to be thrown

function(data) {
        if(data === undefined) {
                throw new Error(&#39;Missing&#39;)   
        } 
        return bar
}
简写:
mandatory = () => {
        throw new Erroe (&#39;Missing&#39;)
}
foo = (bar = mandatory()) => {
        return bar
}
Copy after login

The above is the detailed content of Some effective JS tips. 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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles