Tips and traps that js beginners should know
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"
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' // 替换所有匹配的字符串
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
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
If you want to know if your variable is an array, you can still use Array.isArray(myVar)
6. Closure
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
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 betweenAlternative Method: Use##let
and
varis the scope. The scope of
varis the nearest function block, and the scope of
letis the nearest enclosing block. The enclosing block can be smaller than the function block (if it is not in any block, then
letand
varare both global). (Source)
bind:
Greeters.push(console.log.bind(null, i))
class Foo { constructor (name) {this.name = name } greet () {console.log('hello, this is ', this.name) } someThingAsync () {return Promise.resolve() } asyncGreet () {this.someThingAsync() .then(this.greet) } }new Foo('dog').asyncGreet()
Cannot read property 'name' of undefined, give you one point.
greet is not running in the correct context. Again, there are still many solutions to this problem.
asyncGreet () {this.someThingAsync() .then(this.greet.bind(this)) }
greet.
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) } }
=> ) can be used to preserve context. This method will also work:
asyncGreet () {this.someThingAsync() .then(() => {this.greet() }) }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

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