3 simple but tricky JavaScript Interview Questions

3 simple but tricky JavaScript Interview Questions

JavaScript array length property

A question
of what clothes [0] values are?

const clothes = ['jacket', 't-shirt'];
clothes.length = 0;

clothes[0]; // => ???

Answer
length property array object with a particular behavior: reduce the length of the side effects of property values is to delete their own array element. So when JavaScript execution clothes.length = 0 will delete all the elements.
clothes [0] is equal to undefined because the array has been emptied clothes.

Automatic semicolon insertion

Question two
arrayFromValue () Returns the value of what?

function arrayFromValue(item) {
  return
    [item];
}

arrayFromValue(10); // => ???

Answer
is easy to miss the return line breaks between the keywords and expressions [item]. This break is automatically inserted JavaScript, semicolon between the return and the expressions [Item]

function arrayFromValue(item) {
  return;
  [item];
}

arrayFromValue(10); // => undefined

return; internal function so that it returns undefined. Thus arrayFromValue (10) is undefined.

Floating-point calculation

Question three
What is the result of the equation?

0.1 + 0.2 === 0.3 // => ???

Answer
First, we must first know the value of 0.1 + 0.2:

0.1 + 0.2; // => 0.30000000000000004

The sum of 0.1 and 0.2 0.3 not entirely, but slightly higher than 0.3.

Since binary coded floating point numbers, the floating-point addition operation so as to generate class rounding error.

In short, a direct comparison is not accurate floating-point number.

Thus === 0.3 0.1 + 0.2 The results are false.

Published 12 original articles · won praise 17 · views 2979

Guess you like

Origin blog.csdn.net/qq1140037586/article/details/105308181