Home >Web Front-end >JS Tutorial >Tips and traps that js beginners should know

Tips and traps that js beginners should know

PHP中文网
PHP中文网Original
2017-06-21 09:39:501005browse

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

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

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

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

You should also know about arrow functions (

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

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

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