This is the fifth day of my participation in the August Wen Challenge.More challenges in August
JS data type is one of the basic front-end knowledge, is also one of the most common interview questions in the process of interview, when asked about the topic, you just generally introduce a variety of types, this article takes you to explain the JS data type in detail.
Read this article and you will learn
- Two data types
- A method for determining data types
- Implicit conversion of data types
Primitive data types (primitive data types)
species
- Number, Boolean, string, null, undefined, symbol(ES6 new), bigInt(new)
features
- Simple data segments held in stack memory
- Data is immutable, that is, cannot be forcibly modified
Array.prototype.sort.call('abc'); (Errors will be reported)
- There is no prototype in the chain
_proto_
attribute
detection
- use
typeof
Basic data types can be detected - but
typeof(null) == 'object'
null
Get the detection error is a legacy issue inJS
The initial version of the version used a 32-bit system that used low stored variable type information for performance purposes.000
The beginning represents the object howevernull
Represents all zero, so it’s misjudged to be zeroobject
。
Reference data type
species
- Object (including ordinary Object -Object, Array Object -Array, regular Object -RegExp, Date Object -Date, Math Function -Math, Function Object -Function)
features
- Two Spaces are allocated when a reference type is being created
- The reference type itself is stored in a heap (of course, the amount of data is large).
- A block on the stack that stores references to data on the heap (memory addresses on the heap, i.e. Pointers)
- Reference types are mutable: i.e
let a={}; a.x=1;
function
The parameter is value passing,References cannot be modified
detection
- through
Object.prototype.toString.call
The most accurate detection
/ / Vue source detection method let _toString = Object. The prototype. ToString; Function toRawType (value) {return string _tostring.call (value).slice(8, -1)} // Strict object type check, Function isPlainObject (obj) {return _tostring. call(obj) === '[object object]'}Copy the code
Various methods of data type determination
typeof
- Typeof return values correspond to tables
type | The results of |
---|---|
String | “string” |
Number | “number” |
Boolean | “boolean” |
Undefined | “undefined” |
Object, Array, RegExp, NULL, Date, Error | “object” |
Function | “function” |
Symbol (new) ES6 | “symbol” |
instanceof
- The instanceof operator needs to specify a constructor, or a specific type, that determines whether the constructor’s stereotype is in the stereotype chain of a given object
123 instanceof Number, //false 'dsfsf' instanceof String, //false false instanceof Boolean, //false [1,2,3] instanceof Array, //true {a:1,b:2,c:3} instanceof Object, //true function(){console.log('aaa'); } instanceof Function, //true undefined instanceof Object, //false null instanceof Object, //true /^[a-za-z]{5,20}$/ instanceof RegExp, //true new Error() instanceof Error //trueCopy the code
- Number, String, Boolean does not detect their type, but it does if you use the following writing rules:
var num = new Number(123);
var str = new String('dsfsf');
var boolean = new Boolean(false);
Copy the code
-
Also note that null and undefined both return false. This is because their types are themselves. Object did not create them, so they return false.
-
Implement an Instanceof method manually
Function myInstanceof(left, right) {return false if(typeof left! == 'object' || left === null) return false; Let proto = object.getProtoTypeof (left); let proto = object.getProtoTypeof (left); If (proto == null) return false; if(proto == null) return false; If (proto == right.prototype) return true; proto = Object.getPrototypeof(proto); } } console.log(myInstanceof("111", String)); //false console.log(myInstanceof(new String("111"), String)); //trueCopy the code
constructor
constructor
是prototype
Object that points to the constructor- According to the order in which the instance object looks for attributes, if there are no instance attributes or methods on the instance object, it goes to the prototype chain to look for them. Therefore, the instance object can also be used
constructor
Properties.
var num = 123; var str = 'abcdef'; var bool = true; var arr = [1, 2, 3, 4]; var json = {name:'wenzi', age:25}; var func = function(){ console.log('this is function'); } var und = undefined; var nul = null; var date = new Date(); Var/reg = ^ [a zA - Z] {5, 20} $/; var error= new Error(); function Person(){} var tom = new Person(); Console. log(tom.constructor==Person, num. Constructor ==Number, str.constructor==String, bool.constructor==Boolean, arr.constructor==Array, json.constructor==Object, func.constructor==Function, date.constructor==Date, reg.constructor==RegExp, error.constructor==Error ); // All results are trueCopy the code
toString()
- Can be achieved by
toString()
To get the type of each object. - In order for every object to pass
Object.prototype.toString()
To test it, you need toFunction.prototype.call()
orFunction.prototype.apply()
Is called in the form of
var toString = Object.prototype.toString; toString.call(123); //"[object Number]" toString.call('abcdef'); //"[object String]" toString.call(true); //"[object Boolean]" toString.call([1, 2, 3, 4]); //"[object Array]" toString.call({name:'wenzi', age:25}); //"[object Object]" toString.call(function(){ console.log('this is function'); }); //"[object Function]" toString.call(undefined); //"[object Undefined]" toString.call(null); //"[object Null]" toString.call(new Date()); / / "[object Date]" toString. Call (/ ^ [a zA - Z] {5, 20} $/); //"[object RegExp]" toString.call(new Error()); //"[object Error]"Copy the code
A function that gets the exact type of a variable
function getDataType(obj) { let type = typeof obj; if (type ! == 'object') { return type; } // If the data type is not object, you can use typeof to determine whether the data type is object. Must use accurate judgment type Object. The prototype. ToString. Call (obj) way to judge the return Object. The prototype. ToString. Call (obj). Replace (/ ^ \ [Object (\S+)\]$/, '$1'); }Copy the code
What is the process by which objects are converted to primitive types?
Converting an object to a primitive type calls the built-in [ToPrimitive] function, for which the logic is as follows:
If the symbol.toprimitive () method is first called and then returns valueOf(), toString() is returned if converted to a primitive type, and an error is reported if neither method returns the primitive type
var obj = { value: 3, valueOf() { return 4; }, toString() { return '5' }, [Symbol.toPrimitive]() { return 6 } } console.log(obj + 1); / / output 7Copy the code
Comparison operations in JS
The ‘true’ value in JS
- JS has only ‘true’ values except ‘false’ values
- There are seven false values
- undefined
- null
- false
- NaN
- ‘ ‘
- 0
- 0
- In implicit conversions of conditional judgments: “false” values are converted to false and “true” values are converted to true;
Frequently asked interview questions about data types
Why doesn’t 0.1 + 0.2 equal 0.3?
- The reason:
- JS has an accuracy range of approximately plus or minus 2^53, truncated beyond this limit. So the 0.1 you see isn’t really 0.1.
- JS will convert decimal to the corresponding binary (binary: 0 and 1).
- 0.1 and 0.2 will loop indefinitely after being converted to binary, truncating the extra bits due to the standard bit limit. This will already result in a loss of precision. The binary truncated by the floating-point decimal limit after being added will become 0.30000000000000004 when converted to decimal.
- Solution: high precision calculation function
- A more detailed answer to this question can be found in this article – 0.1 + 0.2! = = 0.3
[] = =! []
-
All conversions are valueOf() followed by toString()
-
On the right
- Due to the! If the priority is higher than ==, execute first! All,
typeOf()
为object
转Boolean
Are alltrue
! []
Get false- Make an equality judgment
- False is converted to the number 0
- Due to the! If the priority is higher than ==, execute first! All,
-
On the left
- perform
[].valueOf()
The original value or[]
- perform
[].toString()
get""
""
Convert to numbers0
- perform
So: 0 == 0, the answer is true
If (a == 1 &&a == 2
var a = {
value: 0,
valueOf: function() {
this.value++;
return this.value;
}
};
console.log(a == 1 && a == 2);//true
Copy the code
Write in the last
If you find this article beneficial to you, please like it and share it with more people who need it!
Welcome to pay attention to “Quanzhandao road” and wechat official account “Quanzhandao Road”, get more good articles and free books!
If you need [Baidu] & [Bytedance] & [JINGdong] & [Ape Tutoring], please leave a message, you will enjoy VIP speed push service ~
Past oliver
Create a personalized Github profile
The interviewer asks you<img>
What would you say about the element
Special JS floating-point number storage and calculation
Long [word] baidu and good interview after containing the answer | the nuggets technology essay in the future
Front end practical regular expression & tips, all throw you 🏆 nuggets all technical essay | double festival special articles
A detailed explanation of the unpopular HTML tabIndex
A few lines of code teach you to solve the wechat generated posters and two-dimensional code
Principle of Vue3.0 Responsive data: ES6 Proxy
Make the interviewer fall in love with you
How to draw a fine line gracefully
[3 minutes] Front-end performance optimization -HTML, CSS, JS parts
Front-end performance Optimization – Page loading speed optimization
Front-end Performance Optimization – Network transport layer optimization