JavaScript gotchas
Here are some interesting JavaScript facts that I’ve encountered over the last few years.Call Fun 2021-7-18 21:18:39 Author: blog.jonlu.ca(查看原文) 阅读量:6 收藏

Here are some interesting JavaScript facts that I’ve encountered over the last few years.

Call Function.length will return the number of arguments a function is expecting.

Javascript function length

The spread operator will not be included in the count.

Javascript function length

when you call Array.map(func), the mapped function gets called with 3 arguments, not just the value.

So for:

["10", "11", "12"].map(parseInt);

You’d expect to get

but in reality get

This is because .map(parseInt) calls the function with three arguments - (currentValue, index, array). This is normally not an issue, but becomes an issue when the mapped function takes additional arguments that do not correspond to the ones being passed in.

parseInt takes in two arguments - value, [, radix], and thus tries to parse 11 with radix 1, which is NaN

The only falsey values are:

[0, -0, 0n, "", "", null, undefined, NaN, false];

Everything else is truthy - including [], an empty Set(), and an empty object.

I ran into a nasty bug once where a value I thought was guaranteed to be a number was actually explicitly set to null. I was doing a comparison with 0 and ran into this weird behavior:

Javascript null comparison

Call .sort() on an array of numbers will not sort them numerically. Which is perplexing

Null is not equal to zero, and is not greater than zero, but is greater than or equal to zero.

It’s almost a rite of passage for javascript developers to be bewildered that String.replace only replaces the first instance of a match in a string.

Thankfully in ES2021 we now have String.replaceAll, which behaves as you’d expect.

Javascript replace

Someone also pointed out WTFJS.com which is a site that has a lot more javascript oddities and examples.


文章来源: https://blog.jonlu.ca/posts/javascript-facts
如有侵权请联系:admin#unsafe.sh