Home System Tutorial LINUX Javascript is not easy for beginners either

Javascript is not easy for beginners either

Aug 20, 2024 am 07:32 AM
linux linux tutorial Red Hat linux system linux command linux certification red hat linux linux video

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

对于初学者来说 Javascript 也并不简单

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 using alphanumeric (String Unicode code points) by default.

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

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

Very simple 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: Return 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.

对于初学者来说 Javascript 也并不简单

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 functions changing their inputs. You should also know that replace will only replace the first matching string:

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

"bob".replace(/b/g, 'l') === 'lol' // 替换所有匹配的字符串
Copy after login
4. Pay attention when comparing
// These are ok
'abc' === 'abc' // true
1 === 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'  // true
typeof 'a' === 'string' // true
typeof 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)

6. Closure

这是一个很有名的面试题:

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

你是不是认为它会输出 0, 1, 2… ? 你知道它为什么不是这样输出的吗? 你会怎样修改让它输出 0, 1, 2… ?

这里有两种可能的解决方法:

用 let 替代 var. Boom. 解决了.

letvar的不同在于作用域。var的作用域是最近的函数块,let的作用域是最近的封闭块,封闭块可以小于函数块(如果不在任何块中,则letvar都是全局的)。(来源)

替代方法: 用 bind:

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

还有很多其他方法。这只是我的两个首选

7. 谈到 bind

你认为这个会输出什么?

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()
Copy after login

如果你认为这个程序会崩溃提示 Cannot read property 'name' of undefined,给你一分。

原因: greet 没有在正确的上下文中运行。同样,这个问题依然有很多解决方案。

我个人喜欢

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

这样可以确保类的实例作为上下文调用greet

如果你认为greet 不应该在实例上下文之外运行, 你可以在类的constructor中绑定它:

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

你还应该知道箭头函数( => )可以用来保留上下文。这个方法也可以:

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

尽管我认为最后一种方法并不优雅。

对于初学者来说 Javascript 也并不简单

我很高兴我们解决了这个问题。

总结

祝贺你,你现在可以放心地把你的程序放在互联网上了。甚至运行起来可能都不会出岔子(但是通常会)Cheers \o/

The above is the detailed content of Javascript is not easy for beginners either. 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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months 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)

Difference between centos and ubuntu Difference between centos and ubuntu Apr 14, 2025 pm 09:09 PM

The key differences between CentOS and Ubuntu are: origin (CentOS originates from Red Hat, for enterprises; Ubuntu originates from Debian, for individuals), package management (CentOS uses yum, focusing on stability; Ubuntu uses apt, for high update frequency), support cycle (CentOS provides 10 years of support, Ubuntu provides 5 years of LTS support), community support (CentOS focuses on stability, Ubuntu provides a wide range of tutorials and documents), uses (CentOS is biased towards servers, Ubuntu is suitable for servers and desktops), other differences include installation simplicity (CentOS is thin)

How to install centos How to install centos Apr 14, 2025 pm 09:03 PM

CentOS installation steps: Download the ISO image and burn bootable media; boot and select the installation source; select the language and keyboard layout; configure the network; partition the hard disk; set the system clock; create the root user; select the software package; start the installation; restart and boot from the hard disk after the installation is completed.

Centos stops maintenance 2024 Centos stops maintenance 2024 Apr 14, 2025 pm 08:39 PM

CentOS will be shut down in 2024 because its upstream distribution, RHEL 8, has been shut down. This shutdown will affect the CentOS 8 system, preventing it from continuing to receive updates. Users should plan for migration, and recommended options include CentOS Stream, AlmaLinux, and Rocky Linux to keep the system safe and stable.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

Centos options after stopping maintenance Centos options after stopping maintenance Apr 14, 2025 pm 08:51 PM

CentOS has been discontinued, alternatives include: 1. Rocky Linux (best compatibility); 2. AlmaLinux (compatible with CentOS); 3. Ubuntu Server (configuration required); 4. Red Hat Enterprise Linux (commercial version, paid license); 5. Oracle Linux (compatible with CentOS and RHEL). When migrating, considerations are: compatibility, availability, support, cost, and community support.

What to do after centos stops maintenance What to do after centos stops maintenance Apr 14, 2025 pm 08:48 PM

After CentOS is stopped, users can take the following measures to deal with it: Select a compatible distribution: such as AlmaLinux, Rocky Linux, and CentOS Stream. Migrate to commercial distributions: such as Red Hat Enterprise Linux, Oracle Linux. Upgrade to CentOS 9 Stream: Rolling distribution, providing the latest technology. Select other Linux distributions: such as Ubuntu, Debian. Evaluate other options such as containers, virtual machines, or cloud platforms.

How to use docker desktop How to use docker desktop Apr 15, 2025 am 11:45 AM

How to use Docker Desktop? Docker Desktop is a tool for running Docker containers on local machines. The steps to use include: 1. Install Docker Desktop; 2. Start Docker Desktop; 3. Create Docker image (using Dockerfile); 4. Build Docker image (using docker build); 5. Run Docker container (using docker run).

What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

See all articles