Мои задачи по Javascript
Случайная задача
Список всех задач

Задача 36

Вопрос на знание алгоритма нестрогого сравнения.
var x = 0;

if ('' == 0 ) { x++; }
if (false == 0 ) { x++; }
if (false == '' ) { x++; }
if (null == 0 ) { x++; }
if (NaN == NaN ) { x++; }
if ([] == '' ) { x++; }
if ({} == '' ) { x++; }

console.log(x);
Что выведет консоль?

Внимание: если вы плохо знаете алгоритм, то можете сразу прочитать пояснение и потом ответить.
1
2
3
4
5
6
7
8
9
← Задача 35Задача 37 →
Пояснение При нестрогом сравнении в JavaScript используется "абстрактный алгоритм эквивалентного сравнения".
Именно из-за этого алгоритма undefined == null возвращает true.

Вот этот алгоритм:

  1. If Type(x) is the same as Type(y), then
    1. If Type(x) is Undefined, return true.
    2. If Type(x) is Null, return true.
    3. If Type(x) is Number, then
      1. If x is NaN, return false.
      2. If y is NaN, return false.
      3. If x is the same Number value as y, return true.
      4. If x is +0 and y is -0, return true.
      5. If x is -0 and y is +0, return true.
      6. Return false.
    4. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions). Otherwise, return false.
    5. If Type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false.
    6. Return true if x and y refer to the same object. Otherwise, return false.
  2. If x is null and y is undefined, return true.
  3. If x is undefined and y is null, return true.
  4. If Type(x) is Number and Type(y) is String,
    return the result of the comparison x == ToNumber(y).
  5. If Type(x) is String and Type(y) is Number,
    return the result of the comparison ToNumber(x) == y.
  6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
  7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
  8. If Type(x) is either String or Number and Type(y) is Object,
    return the result of the comparison x == ToPrimitive(y).
  9. If Type(x) is Object and Type(y) is either String or Number,
    return the result of the comparison ToPrimitive(x) == y.
  10. Return false.

Вот ссылка на ECMAScript: The Abstract Equality Comparison Algorithm.




Написать сообщение - отзыв, пожелание и т.п.