[Front-end interview questions] JavaScript - data types

1. What data types are there

Stack: Basic types: Undefined, Null, Boolean, Number, String
Heap: Reference types: Array, Object, Function
Symbol and BigInt are new data types in ES6:
Symbol: Create unique and immutable data types, mainly to solve Possible global variable conflicts.
BigInt: is a numeric type of data that can represent integers in arbitrary precision format. For securely storing and manipulating big data.

The difference between the two types is the storage location :
1. The original data type is stored in the stack , occupies a small space, has a fixed size, and is frequently used.
2. The reference type objects stored in the heap

2. What are the methods of data type detection

1. typeof: The values ​​of object, null, and array types are all objects, and all other types are correct.

console.log(typeof 2);               // number
console.log(typeof true);            // boolean
console.log(typeof 'str');           // string
console.log(typeof []);              // object    
console.log(typeof function(){
    
    });    // function
console.log(typeof {
    
    });              // object
console.log(typeof undefined);       // undefined
console.log(typeof null);            // object

2. instanceof: Its internal operating mechanism is to determine whether the prototype of this type can be found in its prototype chain . (Cannot detect primitive types, only reference types)

//基本类型无法检测
console.log(2 instanceof Number);                    // false
console.log(true instanceof Boolean);                // false 
console.log('str' instanceof String);                // false 
//引用类型可以检测
console.log([] instanceof Array);                    // true
console.log(function(){
    
    } instanceof Function);       // true
console.log({
    
    } instanceof Object);                   // true

3、constructor

console.log((2).constructor === Number); // true
console.log((true).constructor === Boolean); // true
console.log(('str').constructor === String); // true
console.log(([]).constructor === Array); // true
console.log((function() {
    
    }).constructor === Function); // true
console.log(({
    
    }).constructor === Object); // true

4、Object.prototype.toString.call()

var a = Object.prototype.toString;

console.log(a.call(2));//[object Number]
console.log(a.call(true));//[object Boolean]
console.log(a.call('str'));//[object String]
console.log(a.call([]));//[object Array]
console.log(a.call(function () {
    
     }));//[object Function]
console.log(a.call({
    
    }));//[object Object]
console.log(a.call(undefined));//[object Undefined]
console.log(a.call(null));//[object Null]

3. What are the ways to judge the array

1. Judging by Object.prototype.toString.call()

var arr = [];
console.log(Object.prototype.toString.call(arr).slice(8,-1) === 'Array');//true

2. Judgment through the prototype chain

var arr = [112, 2]
console.log(arr.__proto__ === Array.prototype);//true

3. Judging by ES6's Array.isArray()

var arr = [112, 2]
console.log(Array.isArray(arr));//true

4. Judging by instanceof

var arr = [112, 2]
console.log(arr instanceof Array);//true

5、通过Array.prototype.isPrototypeOf

var arr = [112, 2]
console.log(Array.prototype.isPrototypeOf(arr));//true

Fourth, the difference between null and undefined

The same: all are basic data types, all stored in the stack.
Different:
1. Meaning: null is an empty object, which is mainly used for initialization; undefined is undefined, which defines an unassigned variable, and the value is undefined.
2. Reserved words: null is a reserved word and cannot be used as a variable name; undefined is not a reserved word and can be used as a variable name. The output will not report an error, but conflicts will occur.
3. typeof: typeof null === 'object'; typeof undefined === 'undefined'.

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

5. Why 0.1+0.2 ! == 0.3, and how to make it equal?

console.log(0.1 + 0.2 === 0.3)  // false 为什么呢?

Because the computer stores data in binary, when calculating 0.1+0.2, it needs to be converted into binary and then summed. There are some precision errors, 0.1+0.2=0.30000000000000004.

可以通过四舍五入进行判断

console.log((0.1+0.2).toFixed(2)==0.3);//true

6. What is the result of typeof NaN?

NaN means "not a number", NaN is a "sentinel value" (regular value with a special purpose) used to indicate an error condition in numeric types, i.e. "performing a mathematical operation without success, This is the result returned after failure".

console.log(typeof NaN); // "number"
console.log(NaN !== NaN)

7. What is the difference between the isNaN and Number.isNaN functions?

1. After the function isNaN receives a parameter, it will try to convert the parameter into a numerical value. Any value that cannot be converted into a numerical value will return true. Therefore, if a non-numeric value is passed in, it will also return true, which will affect the judgment of NaN.

console.log(isNaN(1));//false
console.log(isNaN('1'));//false
console.log(isNaN('a'));//true
console.log(isNaN('a'/2));//true

2. The function Number.isNaN will first judge the incoming parameter 是否为数字, 如果是数字and then continue to judge whether it is NaN , and will not convert the data type. This method is more accurate for the judgment of NaN.

console.log(Number.isNaN(1));//false
console.log(Number.isNaN('1'));//false
console.log(Number.isNaN('a'));//false
console.log(Number.isNaN('a' / 2));//true

8. What are the coercion rules for the == operator?

For ==, if the types of the two sides of the comparison are different, type conversion will be performed. If it is compared whether x and y are the same, the following judgment process will be carried out:
1. First, it will judge whether the two 类型are the same , and if they are the same, the size of the two will be compared;
2. If the types are not the same, the type conversion will be performed;
3. Will First judge whether to compare null and undefined, if yes, it will return true;
4. Judge whether the two types are string and number, if yes, it will convert **string to number**;
5. Judge whether one of them is boolean , if yes, it will convert boolean to number and then judge;
6. Judge whether one of them is object and the other is string, number or symbol, if so, it will convert object to primitive type and then judge.
insert image description here

9. Conversion rules from other values ​​to strings?

1. Null and Undefined types, null is converted to "null", undefined is converted to "undefined",
2. Boolean type, true is converted to "true", and false is converted to "false".
3. The value of the Number type is directly converted, but those extremely small and extremely large numbers will use the exponential form.
4. The value of the Symbol type can be directly converted, but only explicit type conversion is allowed. Using the implicit type conversion will cause an error.
5. For ordinary objects, unless the toString() method is defined by itself, toString() (Object.prototype.toString()) will be called to return the value of the internal property [[Class]], such as "[object Object]" . If the object has its own toString() method, that method is called and its return value is used when stringifying.

obj={
    
    }
console.log(Object.prototype.toString.call(obj));//[object Object]

10. What are the conversion rules from other values ​​to numeric values?

1. The value of Undefined type is converted to NaN.
2. The value of Null type is converted to 0.
3. The value of Boolean type, true is converted to 1, and false is converted to 0.
4. The value conversion of String type is like using the Number() function for conversion. If it contains non-numeric values, it is converted to NaN, and the empty string is 0.
5. The value of Symbol type cannot be converted to a number, and an error will be reported.
6. Objects (including arrays) will first be converted to the corresponding basic type value. If the returned value is a non-numeric basic type value, it will be coerced to a number according to the above rules.

11. What are the conversion rules from other values ​​to boolean values?

The following are false values: • undefined • null • false • +0, -0, and NaN • "".
A boolean coercion of a false value results in false. Logically, everything outside the list of false values ​​should be true.

value turn digital convert string convert boolean
undefined NaN “undefined” false
null 0 “null” false
true 1 “true”
false 0 “false”
0 “0” false
-0 “0” false
NaN “NaN” false
Infinity “Infinity” true
-Infinity ”-Infinity” true
1 (non-zero) “1” true
{} (any object) see above see above true
[](任意数组) 0 ”” true
[9](包含一个数字元素) 9 “9” true
[”a”](其他数组) NaN Use the .join() method true
function(){}(any function) NaN see above true

12. Return values ​​of || and && operators?

First, it will be converted to a boolean value.
||: If the judgment result is true, then return the first true value; if the judgment result is false, then return the second false result.
&&: If the result of the judgment is true, then return the second value that is true; if the result of the judgment is false, then return the first value that is false.

console.log( 5 && 4 );//当结果为真时,返回第二个为真的值4 
console.log( 0 && 4 );//当结果为假时,返回第一个为假的值0 
console.log( 5 || 4 );//当结果为真时,返回第一个为真的值5 
console.log( 0 || 0 );//当结果为假时,返回第二个为假的值0 
console.log((3||2)&&(5||0));//5 
console.log(!5);//false 

13. What is the difference between Object.is() and the comparison operators "===" and "=="?

1. === : Compare types and values, if the types are not the same, it is directly false.
2. ==: First judge the type, convert the different types into the same type, and then compare the value
3. Object.is(): The general situation is basically the same as ===, and special situations such as -0 and +0 are no longer equal , two NaNs are equal

Object.is(NaN,NaN);//true

14. What are wrapper types in JavaScript?

Base Type -> Wrapper Type: Object

var a = 'abc'
Object(a) // String {"abc"}

Wrapper Type -> Primitive Type: valueOf

var a = 'abc'
var b = Object(a)
var c = b.valueOf() // 'abc'

In JavaScript, primitive types do not have properties and methods , but in order to facilitate the manipulation of primitive values, JavaScript implicitly converts primitive values ​​to objects in the background when calling properties or methods of primitive types .

var str = '123';
console.log(str.length);//3

'123' -> String('123') -> String('123').length

Guess you like

Origin blog.csdn.net/weixin_46318413/article/details/122771052
Recommended