[suggested stars] 13 implicit type conversion interview questions let you enjoy it all at once

preface

This is one of my series of articles on basic JavaScript, which mainly records type conversion, equality judgment and operator priority in JavaScript. At the end of the article, some common type conversion interview questions are prepared. After reading this article, I believe these questions are so easy for you. The daily blog is recorded in YuQue. Welcome to pay attention to my blog Language bird document.

If the article is helpful to you, you are welcome to like, comment, collect and forward. If you have questions and doubts, you can also leave a message in the comment area. I will reply to you at the first time. If you think there is something wrong in my article, please tell me. Understanding the wrong things in pairs is fatal in any industry.

Type conversion

There is implicit conversion of types in equality judgment. We need to understand the basic rules of data type conversion first. Here we mainly discuss basic data types, common objects, and some special values or types.

Note: the value of the global attribute NaN is not a number. Use isNaN to judge.

ToString

The constructor String() and toString can be used to convert to string. The difference is that toString will report exceptions for null and undefined;

console.log(String(000111)) //73
console.log(000111.toString()) //73

//Number. prototype. ToString (radius) provides a parameter to specify the base, and the default value is 10.
console.log(000111.toString(3)) //2201
console.log(String(1),typeof String(1))// 1 string
console.log(String(-100),typeof String(-100))// -100 string
console.log(String(1.23),typeof String(1.23))// 1.23 string
console.log(String(1e221),typeof String(1e221))// 1e+221 string

console.log(String(3333n),typeof String(3333n)) // 3333 string

console.log(String(Infinity),typeof String(Infinity))// Infinity string

console.log(String(NaN),typeof String(NaN))// NaN string

console.log(String(false),typeof String(false))// false string
console.log(String(true),typeof String(true))// true string

console.log(String(null),typeof String(null))// null string
console.log(String(undefined),typeof String(undefined))// undefined string

console.log(String([]),typeof String([]))// string
console.log(String([1]),typeof String([1]))// 1 string
console.log(String([1,'2',false,null,undefined,NaN,Infinity]),typeof String([1,'2',false,null,undefined,NaN,Infinity]))// 1,2,false,,,NaN,Infinity string

console.log(String({}),typeof String({})) // [object Object] string
console.log(String({a:1}),typeof String({a:1})) // [object Object] string

console.log(String(Symbol("foo")),typeof String(Symbol("foo"))) // Symbol(foo) string

Summary

  1. null, undefined, Boolean, NaN and Symbol are converted to their respective strings;
  2. The numeric type is directly converted to the string of numeric type (including the string in the form of Infinity and negative number). After the exponent is expressed as e, a + sign is added, and other hexadecimal values are converted to decimal;
  3. BigInt type is a string without the following n symbol;
  4. Empty arrays are converted into empty strings. Non empty arrays are equivalent to using join to convert into strings. null and undefined in the array are processed as empty strings;
  5. Object is converted to string as "[object]"

    ToNumber

    The constructor number, parseFloat and parseInt can be used to convert to number. The latter two are independent of implicit type conversion and will not be described in this article.

    console.log(Number('12321'), typeof Number('12321'))// 12321 number
    console.log(Number('1 Mobile 1'), typeof Number('1 Mobile 1'))// NaN number
    console.log(Number('1.23 mobile phone'), typeof Number('1.23 mobile phone'))// NaN number
    console.log(Number(''), typeof Number(''))// 0 number
    
    console.log(Number(3333n), typeof Number(3333n)) // 3333 number
    
    console.log(Number(Infinity), typeof Number(Infinity))// Infinity number
    
    console.log(Number(NaN), typeof Number(NaN))// NaN number
    
    console.log(Number(false), typeof Number(false))// 0 number
    console.log(Number(true), typeof Number(true))// 1 number
    
    console.log(Number(null), typeof Number(null))// 0 number
    console.log(Number(undefined), typeof Number(undefined))// NaN number
    
    console.log(Number([]), typeof Number([]))// 0 number
    console.log(Number([1]), typeof Number([1]))// 1 number
    console.log(Number([1.1]), typeof Number([1.1]))// 1.1 number
    console.log(Number([1.11,2]), typeof Number([1.11,2]))// NaN number
    console.log(Number(['1.11',2]), typeof Number(['1.11',2]))//NaN number
    console.log(Number([1, '2', false, null, undefined, NaN, Infinity]), typeof Number([1, '2', false, null, undefined, NaN, Infinity]))// NaN number
    
    console.log(Number({}), typeof Number({})) // NaN number
    console.log(Number({a: 1}), typeof Number({a: 1})) // NaN number
    
    console.log(Number(Symbol("foo")), typeof Number(Symbol("foo"))) // Cannot convert a Symbol value to a number
    console.log(Number(333n), typeof Number(333n))// 333 number

    Summary

  6. null and empty characters and empty arrays are converted to 0, undefined is converted to NaN, and NaN and Infinity remain unchanged;
  7. A pure numeric string, which is converted to the corresponding number, and others are converted to NaN;
  8. true and false are converted to 1 and 0;
  9. ToPrimitive conversion may be required for array objects. See the following for details;
  10. The first bit of the array is a value, which is converted to this value; otherwise, it is converted to NaN;
  11. Object to NaN;
  12. BigInt is an array without the following n symbols. Symbol s cannot be converted.

    ToBoolean

    To convert to Boolean, you can use the construction method Boolean;

    console.log(Boolean(1),typeof Boolean(1))// true boolean
    console.log(Boolean(-100),typeof Boolean(-100))// true boolean
    console.log(Boolean(1.23),typeof Boolean(1.23))// true boolean
    console.log(Boolean(1e221),typeof Boolean(1e221))// true boolean
    
    console.log(Boolean(3333n),typeof Boolean(3333n)) // true boolean
    
    console.log(Boolean(Infinity),typeof Boolean(Infinity))// true boolean
    
    console.log(Boolean(NaN),typeof Boolean(NaN))// false boolean
    
    console.log(Boolean(false),typeof Boolean(false))// false boolean
    console.log(Boolean(true),typeof Boolean(true))// true boolean
    
    console.log(Boolean(null),typeof Boolean(null))// false boolean
    console.log(Boolean(undefined),typeof Boolean(undefined))// false boolean
    
    console.log(Boolean([]),typeof Boolean([]))//true boolean
    console.log(Boolean([1]),typeof Boolean([1]))// true boolean
    console.log(Boolean([1,'2',false,null,undefined,NaN,Infinity]),typeof Boolean([1,'2',false,null,undefined,NaN,Infinity]))// true boolean
    
    console.log(Boolean({}),typeof Boolean({})) // true boolean
    console.log(Boolean({a:1}),typeof Boolean({a:1})) //true boolean
    
    console.log(Boolean(Symbol("foo")),typeof Boolean(Symbol("foo"))) // true boolean
    

    Except for these 8, the others are true

    console.log(Boolean(false),typeof Boolean(false))// false boolean
    console.log(Boolean(0),typeof Boolean(0))// false boolean
    console.log(Boolean(-0),typeof Boolean(-0))// false boolean
    console.log(Boolean(0n),typeof Boolean(0n))// false boolean
    console.log(Boolean(NaN),typeof Boolean(NaN))// false boolean
    console.log(Boolean(null),typeof Boolean(null))// false boolean
    console.log(Boolean(undefined),typeof Boolean(undefined))// false boolean
    
    //These three are summed up as empty strings
    console.log(Boolean(""),typeof Boolean(""))// false boolean
    console.log(Boolean(''),typeof Boolean(''))// false boolean
    console.log(Boolean(``),typeof Boolean(``))// false boolean

    Summary

    There is a term false in JavaScript. The eight values contained in false are false, and the other values are converted to Boolean and true.

    ToPrimitive

    The explanation of ToPrimitive in MDN is to convert the parameter to the original type by trying to call the valueOf() and toString() methods of the object.

    When the object type needs to be converted to the original type, it will first find the valueOf method of the object. If the valueOf method returns the value of the original type, the result of ToPrimitive is this value. If the valueOf does not exist or the value returned by the valueOf method is not the value of the original type, it will try to call the toString method of the object, that is, it will follow the toString rules of the object, Then use the return value of toString as the result of ToPrimitive.
    Note: the rules of ToPrimitive are different for different types of objects. For example, the Date object will call toString first. For details, please refer to ECMA standard

valueOf and toString usage

let exp=new String(1) //Use String to construct a number 1
console.log(typeof a) //The type is' object '
console.log(exp.valueOf()) // "1"
console.log(typeOf exp.valueOf()) //The original type of 'string' is' 1 'and is of type' string '
console.log(Number([])) // ''=> 0
console.log(Number(['10'])) //'10'=>10

const obj1 = {
    valueOf() {
        return 1
    },
    toString() {
        return 2
    }
}
console.log(Number(obj1))  // 1

const obj2 = {
    toString() {
        return 2
    }
}
console.log(Number(obj2)) // 2

const obj3 = {
    toString() {
        return {}
    }
}
//If neither valueOf nor toString returns a value of the original type, an exception is thrown.
console.log(Number(obj3)) //TypeError: Cannot convert object to primitive value

Summary

When the object type needs to be converted to the original type, ToPrimitive conversion will be performed. Let's give some examples.

  1. String({}). An empty object will call valueOf first, but the object itself {} is returned, which is not the original type. Therefore, toString will be called continuously to get '[object]', String('[object]'), so the result after conversion is' [object] ';
  2. Number([]), the empty array will call valueOf first, but the array itself is returned [], which is not the original type, so it will continue to call toString to get '', which is equivalent to Number(''), so the result after conversion is 0;
  3. Take another look at the examples of valueOf and toString above, obj1 valueOf () returns the basic type 1, so toString will not be executed again. The result of ToPrimitive is 1, which is equivalent to Number(1);
  4. obj2 has no valueOf method. It will execute toString. ToString returns 2. The result of ToPrimitive is 2, which is equivalent to Number(2);
  5. The toString method of obj3 does not return a primitive type and cannot be ToPrimitive, so an error will be thrown;
  6. Note the Boolean() transformation, and all values except false are true;

Here, we have summarized some rules of type conversion. Let's take a look at the equality judgment in JavaScript.

Equality judgment

Four algorithms

  1. Non strict (Abstract) equality comparison:==
  2. Strict equality comparison:===
  3. Zero values are equal: - 0 =
  4. Equal value: object is()

    Non strict equality

    A correspondence table provided by MDN. We need to remember it

    Both undefined and null comparisons are true

    console.log(undefined==null) //true
    console.log(null==null) //true
    console.log(undefined==null) //true

    Other types are false compared with undefined and null

    console.log(1==null) //false
    console.log("null"==null) //false
    console.log(false==null) //false
    console.log(NaN==undefined) //false
    console.log(true==undefined) //false
    console.log(Infinity==undefined) //false
    console.log({}==undefined) //false
    console.log([]==undefined) //false

    8 false values are identified as false, and other values converted to Boolean values are true;

    console.log(!!false) //false
    console.log(!!0)     //false
    console.log(!!-0)    //false
    console.log(!!0n)    //false
    console.log(!!'')    //false
    console.log(!!"")    //false
    console.log(!!null)  //false
    console.log(!!undefined)//false
    console.log(!!NaN)   //false

    Special case, narrow object document All equals null and undefined

    console.log(null==document.all) //true
    console.log(undefined==document.all) //true

    Number, String, Boolean, Object, Array comparison (follow the above table or the following figure):

  5. The same type is congruent comparison;
  6. Other comparisons are converted into numerical values for comparison;

Summary

  1. Both undefined and null comparisons are true;
  2. Other types are false compared with undefined and null;
  3. 8 false values are identified as false, and other values converted to Boolean values are true;
  4. Special case, narrow object document All equals null and undefined
  5. Number, String, Boolean, Object, Array comparison:

    • The same type is congruent comparison;
    • Other comparisons are converted into numerical values for comparison;

Strict equality

There are two special judgments of strict Equality:

  1. +0 equals - 0 (distinguishing between + 0 and - 0 is necessary to solve some specific mathematical problems);
  2. NaN is not equal to NaN.

    console.log(undefined===undefined) //true
    console.log(null===null)//true
    console.log(null===undefined) //false
    
    console.log(+0===-0)   //true
    console.log(0===0)     //true
    console.log(NaN===NaN) //false

    Zero equal & & same value equal

    The different judgments of 0 and NaN in strict equality must be confusing. Using object in JavaScript Is makes the same value equality judgment, which is mainly used to solve the problems of positive zero, negative zero and NaN in strict equality.

    console.log(Object.is(+0,-0)) //false
    console.log(Object.is(NaN,NaN)) //true

    Operator priority

    Some rules summarized:

  3. The type conversion is specified by the operator;
  4. ToPrimitive generally works on = = for example! [] does not require ToPrimitive conversion, which is equivalent to! Boolean([]);
  5. Post + is used as character splicing, and other types are mostly converted to numeric types;
  6. As long as one of the addition operations is a string, the other will also be converted to a string;
  7. If the value is added with null or undefined, the null or undefined is converted to Number().

Partial operator priority:
Tucao markdown's form, here can only be pictures, do not want to make complaints about a lot of HTML. [suggested stars] 13 implicit type conversion interview questions let you enjoy it all at once

Required questions

You have to do it if you don't want to 😣😣😣😣

Topic 1

Define a variable a so that the expression result of a = = 1 & & A = = 2 & & A = = 3 is true.

//This problem can use the valueOf mentioned in our article. Each reading will increase the original value by 1
//let num=0
const a = {
  num: 0,
  valueOf: function() {
    //return num += 1. This is also true. Just save one and change it
    return this.num += 1
  }
};
const equality = (a==1 && a==2 && a==3);
console.log(equality); // true

Using object Defineproperty can also be implemented.

let val=1
Object.defineProperty(window, 'a', {
    get: function() {
        return val++
    }
});

console.log(a == 1 && a == 2 && a == 3)

Topic 2

Why does the expression [] = = 0 result in true.
answer:

  1. First, ToPrimitive transform the array, [] valueOf().toString(), the value is an empty string;
  2. Now it is' '= = 0, and the empty character is converted to a number of 0;
  3. The comparison between 0 and 0 is true, and the judgment is true.

Topic 3

Why expression [] = =! [] the result is true.
answer:

  1. Operator priority and implicit type conversion are considered here. Note that,! Priority ratio = = high, right! [] ToPrimitive conversion is not required, but directly! Boolean([]) result is false;
  2. Now it is [] = = false. At this time, the ToPrimitive conversion will be performed on the left. According to the conversion rules, [] valueOf().toString() is an empty string ''
  3. Now it is' '= = false, and both sides are converted to digital calculation;
  4. The conversion of an empty string to a number is 0, and the conversion of false to a number on the right is 0. 0 and 0 are equal. The judgment is true.

Topic 4

answer:

//If the string '0' is converted to a value of 0, false is also converted to a value of 0
'0' == false // true

//The array has only one value and is a number or string number. The current value is converted to a string,
//If the string is converted to '0', the string '0' is converted to a value of 0, and if false is converted to a value of 0, the judgment is true
['0'] == false // true

//The array has only one value and is a number or string number. The current value is converted to a string,
//If the string is converted to '2', the value of string '2' is converted to 2, and 2 = = 2, it is judged to be true
[2] == 2  //true 

//The empty array is converted to string '', the value of '' is 0, and the value of false is 0
[] == false // true 

//When null and undefined in the array are converted into strings, they are processed as empty strings,
//[null].valueOf().toString() is an empty string '', and the empty string is converted to a number of 0. The judgment is true
[null] == 0 // true

///[null].valueOf().toString() is an empty string '', the empty string is converted to a number of 0, and false is converted to a number of 0
[null] == false // true

//When null and undefined in the array are converted into strings, they are processed as empty strings,
//[undefined].valueOf().toString() is an empty string '', the empty string is converted to a number of 0, and false is converted to a number of 0. The judgment is true.
[undefined] == false // true

//Other types are false compared with undefined and null
undefined == false // false
null == 0 // false
null == false // false

Topic 5

Find the value of true + false.
Answer: convert to digital addition, 1 + 0 = 1

Topic 6

Find "number" + 15 + 3
Answer: the '+' operator is executed from left to right, so it takes priority to execute "number" + 15, convert 15 to string type, get "number", and then execute "number15" + 3 in the same way, and the result is "number153".

Topic 7

Find 100 + true + 21.2 + null + undefined + "tent" + [] + null + 9 + false;
Answer: there is no operator priority here. Just start from the left. ok, let's start decomposition

  1. 100 + true, the numerical value and Boolean value are added, and the Boolean value is converted into a number to obtain 100 + 1 = 101;
  2. 101 + 21.2, the numerical value and the numerical value are added directly to obtain 101 + 21.2 = 122.2;
  3. 122.2+null, the value and null are added, and null becomes 0122.2 + 0 = 122.2;
  4. 122.2 + undefined, the numerical value and undefined are added, and the undefined is converted to the number NaN. The addition of NaN and numerical value is NaN, 122.2+NaN=NaN;
  5. NaN + "tenant", NaN is converted into a string of 'NaN', "NaN" + "tenant" = "tenant";
  6. "NaNTencent" + [], the empty array is converted into a string of "", "NaNTencent" + ""="NaNTencent";
  7. "NaNTencent" + null,null converted to string is "null", "NaNTencent" + "null"="NaNTencentnull";
  8. "NaNTencentnull" + 9, strings and numbers are added, and the plus sign has the function of splicing, converting 9 into string "9", "NaNTencentnull" + "9"="NaNTencentnull9";
  9. "NaNTencentnull9" + false, add the string and Boolean value, and convert false into string "false","NaNTencentnull9" + "false"="NaNTencentnull9false";

    let result = 100 + true + 21.2 + null + undefined + "Tencent" + [] + null + 9 + false;
    console.log(result) //'NaNTencentnull9false'

    Topic 8

    Find the value of {} + [] + {} + [1]
    answer:

  10. The {} on the left will be regarded as an empty execution block rather than an object. This block has no return value, which is equivalent to + [] + {} + [1];
  11. +Is a unary operator, which takes precedence. It turns [] into a number of 0, which is now 0 + {} + [1];
  12. Object to string is "[object]"; 0 + "[object] + [1] gets" 0 [object] + [1];
  13. [1] The converted string is "1", and the result is "0 [object] 1".

    let result = 100 + true + 21.2 + null + undefined + "Tencent" + [] + null + 9 + false;
    console.log(result) //'NaNTencentnull9false'

    Topic 9

    Please+ [] + [] + ! Value of []
    answer:

  14. Sort out the priority first. When logical non and unary are added together, execute from right to left! (+ []) + [] + ! [] ;
  15. +It is treated as a unary operator, (+ []) the result is 0;
  16. Now for! 0+ [] + ! []=>! 0 performs Boolean value replacement on 0, 0 is false, and false is reversed to true;
  17. true+ [] + ! [] ` [] to Boolean value is true, and negation is false `;
  18. [] is converted to string '';
  19. true+ '' + false splice the three together to get "truefalse".

    Topic 10

    Find [1] > null
    Answer: the comparison operator > performs an implicit conversion of type number, [1] is converted to a number of 1, null is 0, and 1 > 0 is true.

    Topic 11

    Find "foo" + + "bar"
    Answer: convert it to "foo" + (+"bar");
    The priority on the right side is higher, (+ "bar") triggers the implicit conversion of number type, and the converted number is NaN, "foo" +NaN
    Splice as' fooNaN '.

Topic 12

Find 0 | "0" & & {}
Answer: Boolean type conversion is performed by the logical operator. The conversion from 0 to Boolean value is false, and the right side of 0 | "0" is true
"0" & & {}, string "0" is Boolean true, return to the right and get {}.

Topic 13

Find [1,2,3] = [1,2,3]
Answer: if the type is the same, the strict equality judgment is not performed on the line type conversion. The array is a reference type, and the memory addresses of the two are different. It is false.

epilogue

It's been so long and hard, but I've written for a long time. You might as well give me a praise before you go. 😁😁😁
You can also take a look at the other two articles in my series, hey hey

🎉🎉On New Year's day in 2022, I finally understood the prototype and prototype
🎉🎉⌈ 2022 ⌋ JavaScript super detailed loop summary

quote

First published in YuQue document @ is_tao
Equality judgment in JavaScript
Starting from an interview question - js implicit conversion pit collection
False imaginary value
Research on JavaScript data type conversion through interview questions

Keywords: Javascript Front-end Interview

Added by igor berger on Fri, 07 Jan 2022 12:34:04 +0200