当前位置:网站首页>Js25 topic

Js25 topic

2022-06-23 18:35:00 Front end development enthusiasts

25 Tao magic javascript Example , All right, I lose !!!

 Package diagram _8cd24cff009c160a3cade7f7142dd655_46474
Package diagram _8cd24cff009c160a3cade7f7142dd655_46474

Preface

JavaScript It's a good language . It has a simple syntax , Huge ecosystem , And most importantly , The greatest community . meanwhile , We all know ,JavaScript It's a very interesting and tricky language . Some of them can quickly turn our daily work into hell , Some can make us laugh loudly .

background

The main purpose of these examples is to collect some crazy examples , And explain how they work , If possible . Just because it's fun to learn something you didn't know before . If you are a beginner , You can read this article to learn more about JavaScript. I hope this article will inspire you to spend more time reading the code . If you are a professional developer , You can think of these examples as an important resource for novices in your company to access questions and quizzes . meanwhile , These examples can be handy when preparing for an interview . in any case , Read it . Maybe you will find something new for yourself .

Example

1. true + false

Number(true); // -> 1
Number(false); // -> 0
1 + 0// -> 1

explain :

Boolean values are converted to their numerical representation

2. true yes false

!!"false" == !!"true"// -> true
!!"false" === !!"true"// -> true

explain :

Consider this step :

true == "true"// -> true
false == "false"// -> false

// 'false'  Not an empty string , So its value is  true
!!"false"// -> true
!!"true"// -> true

3. baNaNa

"b" + "a" + +"a" + "a"// baNaNa

use JavaScript Old school jokes written :

"foo" + +"bar"// -> 'fooNaN'

explain :

This expression can be converted to 'foo' + (+'bar'), But we can't put 'bar' Force conversion to numeric .

4. NaN Is not a NaN

NaN === NaN// -> false

explain :

The specification strictly defines the logic behind this behavior :

  1. If Type(x) differ Type(y), return false.
  2. If Type(x) The number , then
    1. If x yes NaN, return false.
    2. If y yes NaN, return false.
    3. … … …

follow IEEE Of “NaN” The definition of :

There are four possible mutually exclusive relationships : Less than , be equal to , Greater than and out of order . When at least one operand is NaN when , This is the last case . Every NaN To compare the endless , Including myself .

5. It is fail

You won't believe , but ...

(![] + [])[+[]] +
  (![] + [])[+!+[]] +
  ([![]] + [][[]])[+!+[] + [+[]]] +
  (![] + [])[!+[] + !+[]];
// -> 'fail'

explain :

Break a large number of symbols into fragments , We noticed that , The following expression often appears :

![] + []; // -> 'false'
![]; // -> false

So we try to [] and false Add up . But through some internal function calls (binary + Operator - >ToPrimitive - >[[DefaultValue] ]), We finally convert the operand on the right to a string :

![] + [].toString(); // 'false'

String as an array , We can go through [0] To access its first character :

"false"[0]; // -> 'f'

Now? , The rest is obvious , You can figure it out for yourself !

6. [] yes true, But it doesn't mean true

!![]       // -> true
[] == true // -> false

explain :

An array is a true, But it doesn't mean true.

7. null yes false, But it doesn't mean false

Even though null yes false, But it doesn't mean false.

!!null// -> false
null == false// -> false

meanwhile , Others are equal to false Value , Such as 0 or '' be equal to false .

0 == false// -> true
"" == false// -> true

explain :

Same as the previous example . This is a corresponding link :

8. document.all It's a object, But at the same time undefined

️ This is the browser API Part of , about Node.js Invalid environment ️

Even though document.all It's a array-like object And through it, you can access DOM node , But through typeof The result of the test is undefined.

document.all instanceof Object// -> true
typeof document.all; // -> 'undefined'

meanwhile ,document.all It's not equal to undefined.

document.all === undefined// -> false
document.all === null// -> false

But at the same time :

document.all == null// -> true

explain :

document.all Used to be visiting pages DOM A way of nodes , Especially in earlier versions of IE Browser . It has never been the standard , But it was widely used in the early JS In the code . When standards evolve into new API when ( for example document.getElementById) This API The call is discarded , The standards committee must decide how to deal with it . Because it was widely used, well, they decided to keep this API But introduce a deliberate pair of JavaScript A violation of the standards of . And undefined Use Strictly equal comparison obtain false While using Abstract equality comparison obtain true Because this intentional violation of the standard explicitly allows this .

9. The minimum value is greater than zero

Number.MIN_VALUE Is the smallest number , Greater than zero :

Number.MIN_VALUE > 0// -> true

explain :

Number.MIN_VALUE yes 5e-324 , That is, the smallest positive number that can be expressed in floating-point precision , That is, it can reach zero . It defines the highest precision of floating point numbers .

Now? , The overall minimum value is Number.NEGATIVE_INFINITY , Although this is not a real number in the strict sense .

10. Function is not a function

️ V8 v5.5 Or earlier Bug(Node.js <= 7) ️

All of you know about annoying undefined No function , But this one ?

// Declare a class which extends null
class Foo extends null {}
// -> [Function: Foo]

new Foo() instanceof null;
// > TypeError: function is not a function
// >     at … … …

explain :

This is not part of the specification . It was just a mistake , Now it has been fixed , So there will be no such problem in the future .

11. Array addition

What if you try to add two arrays ?

[123] + [456]; // -> '1,2,34,5,6'

explain :

There will be a merger . Step by step , It looks like this :

[123] +
  [456][
    // joining
    (123)
  ].join() +
  [456].join();
// concatenation
"1,2,3" + "4,5,6";
// ->
("1,2,34,5,6");

12. Commas in the array

You have created a containing 4 Array of empty elements . For all that , You'll still get a three element , Because the comma after it :

let a = [, , ,];
a.length; // -> 3
a.toString(); // -> ',,'

explain :

Trailing comma ( Sometimes it's also called “ Last comma ”) In the JavaScript Add new elements to the code 、 Parameter or attribute . If you want to add a new attribute , You can simply add a new row , Instead of changing the previous last line , If the line has used the following comma . This makes version control cleaner and editing code less cumbersome .

13. Array equality is a monster

Array equality comparison is a monster , See the following example :

[] == ''   // -> true
[] == 0    // -> true
[''] == '' // -> true
[0] == 0   // -> true
[0] == ''  // -> false
[''] == 0  // -> true

[null] == ''      // true
[null] == 0       // true
[undefined] == '' // true
[undefined] == 0  // true

[[]] == 0  // true
[[]] == '' // true

[[[[[[]]]]]] == '' // true
[[[[[[]]]]]] == 0  // true

[[[[[[ null ]]]]]] == 0  // true
[[[[[[ null ]]]]]] == '' // true

[[[[[[ undefined ]]]]]] == 0  // true
[[[[[[ undefined ]]]]]] == '' // true

explain :

You should pay very careful attention to the above example ! 7.2.13 Abstract Equality Comparison The specification describes these behaviors .

14. undefined and Number

If we don't pass any parameters to Number In the constructor , We will get 0 .undefined Is an assignment parameter , There are no actual parameters , So you might expect NaN take undefined As the value of the parameter . However , When we go through undefined , We will get NaN .

Number(); // -> 0
Number(undefined); // -> NaN

explain :

According to the specification :

  1. If no arguments are passed to this function , Give Way n by +0 ;
  2. otherwise , Give Way n call ToNumber(value)
  3. If the value is undefined, that ToNumber(undefined) Should return to NaN.

15. parseInt It's a bad guy

parseInt It is famous for its weirdness .

parseInt("f*ck"); // -> NaN
parseInt("f*ck"16); // -> 15

** explain :

** This is because parseInt It will continue to parse until it resolves to an unrecognized character ,'f*ck' Medium f yes 16 In base number 15.

analysis Infinity It's also interesting to go to whole numbers …

//
parseInt("Infinity"10); // -> NaN
// ...
parseInt("Infinity"18); // -> NaN...
parseInt("Infinity"19); // -> 18
// ...
parseInt("Infinity"23); // -> 18...
parseInt("Infinity"24); // -> 151176378
// ...
parseInt("Infinity"29); // -> 385849803
parseInt("Infinity"30); // -> 13693557269
// ...
parseInt("Infinity"34); // -> 28872273981
parseInt("Infinity"35); // -> 1201203301724
parseInt("Infinity"36); // -> 1461559270678...
parseInt("Infinity"37); // -> NaN

Also be careful to parse null

parseInt(null24); // -> 23

explain :

It will null Convert to string 'null' , And try to convert it . For cardinality 0 To 23, There are no numbers that can be converted , Therefore return NaN. stay 24,“n” , The first 14 Letters are added to the number system . stay 31,“u” , Add para 21 Letters , You can decode the entire string . stay 37 It's about , There is no longer a valid set of digits that can be generated , And back to NaN .

Don't forget octal :

parseInt("06"); // 6
parseInt("08"); // 8  If the support  ECMAScript 5
parseInt("08"); // 0  If not  ECMAScript 5

explain :

This is because parseInt Can accept two parameters , If a second parameter is not provided , And the first parameter starts with 0 Start , It will parse the first parameter as an octal number .

parseInt Always convert input to a string :

parseInt({ toString() => 2valueOf() => 1 }); // -> 2
Number({ toString() => 2valueOf() => 1 }); // -> 1

Be careful when parsing floating point numbers

parseInt(0.000001); // -> 0
parseInt(0.0000001); // -> 1
parseInt(1 / 1999999); // -> 5

explain :ParseInt Accepts a string parameter and returns a certificate under a specified cardinality .ParseInt Also remove non numeric characters from the first string ( The character set is determined by the cardinality ) Later content .0.000001 Converted to "0.000001" and parseInt return 0. When 0.0000001 When converted to a string, it is processed as "1e-7" therefore parseInt return 1.1/1999999 Converted to 5.00000250000125e-7 and parseInt return 5.

16. true and false Mathematical operations

We do some mathematical calculations :

true +
  true(
    // -> 2
    true + true
  ) *
    (true + true) -
  true// -> 3

Um. …

explain :

We can use Number Constructors are forced to convert to numeric values . Obviously ,true Will be cast to 1

Number(true); // -> 1

The unary addition operator attempts to convert its value to a number . It can convert integer and floating-point string representations , And non string values true ,false and null . If it can't parse a specific value , It will turn into NaN . This means that we can more easily force true Switch to 1

+true// -> 1

When you add or multiply ,ToNumber Method call . According to the specification , This method returns :

If Parameters is true , return 1 . If Parameters yes false return +0.

That's why we can add Boolean values and get the correct result

The corresponding part :

17. HTML The note is in JavaScript Effective in

You will be impressed ,<!-- ( This is a HTML notes ) Is an effective JavaScript notes .

//  Valid comments 
<!--  It is also a valid comment

explain :

Moved ? similar HTML The annotation of is designed to allow browsers that do not understand the tag to downgrade gracefully . These browsers , for example Netscape 1.x It's no longer popular . therefore , Add... To the script tag HTML Comments are meaningless .

because Node.js be based on V8 engine ,Node.js The runtime also supports similar HTML Notes .

18. NaN No A number

Even though NaN The type is 'number' , however NaN Not an instance of a number :

typeof NaN// -> 'number'
NaN instanceof Number// -> false

explain :

typeof and instanceof How operators work :

19. [] and null It's the object

typeof []; // -> 'object'
typeof null// -> 'object'

//  However
null instanceof Object// false

explain :

typeof The behavior of the operator is defined in the specifications in this section :

According to the specification ,typeof The operator returns a string . For no [[Call]] Realized null、 Common object 、 Standard specific objects and non-standard specific objects , It returns a string "object“.

however , You can use toString Method to check the type of the object .

Object.prototype.toString.call([]);
// -> '[object Array]'

Object.prototype.toString.call(new Date());
// -> '[object Date]'

Object.prototype.toString.call(null);
// -> '[object Null]'

20. Amazing digital growth

999999999999999// -> 999999999999999
9999999999999999// -> 10000000000000000

explain :

This is from IEEE 754-2008 Caused by the binary floating point arithmetic standard .

21. 0.1 + 0.2 Accuracy calculation

come from JavaScript Famous joke .0.1 and 0.2 There is a precision error in addition

0.1 +
  0.2(
    // -> 0.30000000000000004
    0.1 + 0.2
  ) ===
  0.3// -> false

explain :

Floating point calculation is broken :

Constants in the program 0.2 and 0.3 It will also approximate the true value . Nearest 0.2 Of double Greater than rational number 0.2 , But closest to 0.3 Of double Less than rational number 0.3.0.1 and 0.2 The sum of is greater than the rational number 0.3, Therefore, it does not conform to the constant judgment in your code .

This problem is well known , There is even a website called 0.30000000000000004.com.

22. Ways to expand numbers

You can add your own methods to wrap objects , Such as Number or String .

Number.prototype.isOne = function({
  return Number(this) === 1;
};

(1.0).isOne(); // -> true
(1).isOne(); // -> true
(2.0)
  .isOne()(
    // -> false
    7
  )
  .isOne(); // -> false

explain :

obviously , You can look like JavaScript Like any other object in the Number object . however , It is not recommended to extend behavior definitions that are not part of the specification . Here are Number A list of properties :

23. Comparison of three numbers

1 < 2 < 3// -> true
3 > 2 > 1// -> false

explain :

Why is this so ? The problem is the first part of the expression . Here's how it works :

1 < 2 < 3// 1 < 2 -> true
true < 3// true -> 1
1 < 3// -> true

3 > 2 > 1// 3 > 2 -> true
true > 1// true -> 1
1 > 1// -> false

We can use _ Greater than or equal to operator (>=)_:

3 > 2 >= 1// true

24. Interesting math

Usually JavaScript The results of arithmetic operations in can be very unpredictable . Consider these examples :

 3  - 1  // -> 2
 3  + 1  // -> 4
'3' - 1  // -> 2
'3' + 1  // -> '31'

'' + '' // -> ''
[] + [] // -> ''
{} + [] // -> 0
[] + {} // -> '[object Object]'
{} + {} // -> '[object Object][object Object]'

'222' - -'111' // -> 333

[4] * [4]       // -> 16
[] * []         // -> 0
[44] * [44// NaN

explain :

What happened in the first four examples ? This is a small watch , To understand JavaScript Add... To :

Number  + Number  -> addition
Boolean + Number  -> addition
Boolean + Boolean -> addition
Number  + String  -> concatenation
String  + Boolean -> concatenation
String  + String  -> concatenation

The remaining examples ? Before adding ,[] and {} Implicit call ToPrimitive and ToString Method .

25. String is not String Example

"str"// -> 'str'
typeof "str"// -> 'string'
"str" instanceof String// -> false

explain :

String Constructor returns a string :

typeof String("str"); // -> 'string'
String("str"); // -> 'str'
String("str") == "str"// -> true

Let's try one new

new String("str") == "str"// -> true
typeof new String("str"); // -> 'object'

object ? What is that ?

new String("str"); // -> [String: 'str']

notes : Part of the content is from jsisweird

After reading two things

If you think it's enlightening , I'd like to invite you to help me with two small things

1. Order one 「 Looking at 」, Let more people see this article ( O 'clock 「 Looking at 」,bug -1 ) 2. Pay attention to WeChat public number 「 Front end development enthusiasts 」, Keep pushing selected articles for you 、 3. Pay attention to the reply of the official account 「 Add group 」, Invite you to join the front-end communication group , Learn new technologies together 4. Fan benefits : There are several selected courses in the menu at the bottom of the official account , Pay attention to taking things for yourself

原网站

版权声明
本文为[Front end development enthusiasts]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231731487224.html