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?
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
new Date() Acceptable:
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 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' // 替换所有匹配的字符串
// 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
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 ===.
typeof {} === 'object' // true typeof 'a' === 'string' // true typeof 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)
这是一个很有名的面试题:
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
你是不是认为它会输出 0, 1, 2… ? 你知道它为什么不是这样输出的吗? 你会怎样修改让它输出 0, 1, 2… ?
这里有两种可能的解决方法:
用 let 替代 var. Boom. 解决了.
let和var的不同在于作用域。var的作用域是最近的函数块,let的作用域是最近的封闭块,封闭块可以小于函数块(如果不在任何块中,则let和var都是全局的)。(来源)
替代方法: 用 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,给你一分。
原因: greet 没有在正确的上下文中运行。同样,这个问题依然有很多解决方案。
我个人喜欢
asyncGreet () { this.someThingAsync() .then(this.greet.bind(this)) }
这样可以确保类的实例作为上下文调用greet。
如果你认为greet 不应该在实例上下文之外运行, 你可以在类的constructor中绑定它:
class Foo { constructor (name) { this.name = name this.greet = this.greet.bind(this) } }
你还应该知道箭头函数( => )可以用来保留上下文。这个方法也可以:
尽管我认为最后一种方法并不优雅。 我很高兴我们解决了这个问题。 祝贺你,你现在可以放心地把你的程序放在互联网上了。甚至运行起来可能都不会出岔子(但是通常会)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!asyncGreet () {
this.someThingAsync()
.then(() => {
this.greet()
})
}