Table of Contents
1. Have you ever tried to sort a set of numbers?
2. new Date() is great
3. Replace does not "replace"
4. When comparing, please pay attention to
5. Array is not a primitive data type
Closure" >6. Closure
Home Web Front-end JS Tutorial Tips and traps that js beginners should know

Tips and traps that js beginners should know

Jun 21, 2017 am 09:39 AM
javascript js Simple

Here are some tips and pitfalls that Javascript beginners should know. If you're already an expert, brush up on this.

Javascript is just a programming language. How could it possibly go wrong?

1. Have you ever tried to sort a set of numbers?

Javascript's sort() function sorts alphanumeric (String Unicode code points) by default.

So [1,2,5,10].sort() will output [1, 10, 2, 5].

To correctly sort an array, you can use [1,2,5,10].sort((a, b) => a — b)

A very simple solution Solution, the premise is that you have to know that there is such a pit

2. new Date() is great

new Date() Acceptable:

  • No parameters: Returns the current time

  • One parameter x: Returns January 1, 1970 + x milliseconds. Those who know Unix know why.

  • new Date(1, 1, 1) returns 1901, February, 1st\. Because, the first parameter represents 1900 plus 1 year, the second parameter represents the second month of this year (so February) — People with normal brain circuits will start indexing from 1 — , and the third parameter is very Obviously it's the first day of the month, so 1 — sometimes the index does start at 1 — .

  • new Date(2016, 1, 1) will not add 2016 to 1900. It only represents 2016.

3. Replace does not "replace"

let s = "bob"const replaced = s.replace('b', 'l')
replaced === "lob"
s === "bob"
Copy after login

I think this is a good thing because I don't like function changes their input. You should also know that replace will only replace the first matching string:

If you want to replace all matching strings, you can use it with the /g flag Regular expression:

"bob".replace(/b/g, 'l') === 'lol' // 替换所有匹配的字符串
Copy after login

4. When comparing, please pay attention to

// These are ok'abc' === 'abc' // true1 === 1         // true// These are not
[1,2,3] === [1,2,3] // false
{a: 1} === {a: 1}   // false
{} === {}           // false
Copy after login

Reason: [1,2,3] and [1,2,3] are two independent arrays. They just happen to contain the same value. They have different references and cannot be compared with ===.

5. Array is not a primitive data type

typeof {} === 'object'  // truetypeof 'a' === 'string' // truetypeof 1 === number     // true// But....typeof [] === 'object'  // true
Copy after login

If you want to know if your variable is an array, you can still use Array.isArray(myVar)

This is a well-known interview question:

const Greeters = []for (var i = 0 ; i < 10 ; i++) {
  Greeters.push(function () { return console.log(i) })
}
Greeters[0]() // 10
Greeters[1]() // 10
Greeters[2]() // 10
Copy after login

Do you think it will output 0, 1, 2...? Do you know why it doesn't output like this? How would you modify it so that it outputs 0, 1, 2...?

There are two possible solutions here:

Replace var with let. Boom. Solved.

# The difference between

##let and var is the scope. The scope of var is the nearest function block, and the scope of let is the nearest enclosing block. The enclosing block can be smaller than the function block (if it is not in any block, then let and var are both global). (Source)

Alternative Method: Use

bind:

Greeters.push(console.log.bind(null, i))
Copy after login

There are many other ways. These are just my two top picks

7. Speaking of bind

what do you think this will output?

class Foo {  constructor (name) {this.name = name
  }
  greet () {console.log(&#39;hello, this is &#39;, this.name)
  }
  someThingAsync () {return Promise.resolve()
  }
  asyncGreet () {this.someThingAsync()
    .then(this.greet)
  }
}new Foo(&#39;dog&#39;).asyncGreet()
Copy after login

If you think this program will crash and prompt

Cannot read property 'name' of undefined, give you one point.

Cause:

greet is not running in the correct context. Again, there are still many solutions to this problem.

I personally like

asyncGreet () {this.someThingAsync()
.then(this.greet.bind(this))
}
Copy after login

This ensures that the instance of the class is called as the context

greet.

If you think

greet should not run outside the instance context, you can bind it in the class's constructor:

class Foo {constructor (name) {this.name = namethis.greet = this.greet.bind(this)
}
}
Copy after login

You should also know about arrow functions (

=> ) can be used to preserve context. This method will also work:

asyncGreet () {this.someThingAsync()
.then(() => {this.greet()
})
}
Copy after login
Although I think the last method is not elegant.

I'm glad we solved this problem.

Summary

Congratulations, you can now safely put your program on the Internet. It might not even run wrong (but it usually does) Cheers \o/

If there's anything else I should mention, please let me know!

The above is the detailed content of Tips and traps that js beginners should know. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

The easiest way to query the hard drive serial number The easiest way to query the hard drive serial number Feb 26, 2024 pm 02:24 PM

The hard disk serial number is an important identifier of the hard disk and is usually used to uniquely identify the hard disk and identify the hardware. In some cases, we may need to query the hard drive serial number, such as when installing an operating system, finding the correct device driver, or performing hard drive repairs. This article will introduce some simple methods to help you check the hard drive serial number. Method 1: Use Windows Command Prompt to open the command prompt. In Windows system, press Win+R keys, enter "cmd" and press Enter key to open the command

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

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

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

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

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

See all articles