Bits and pieces of knowledge
1, js for loop for in for of
for in
This is a regular cyclefor (var i=0; i<5; i++) {
x=x + "The number is" + i + "<br>";
}
Copy the code
3. for-in: first, the most common use of for-in is to loop over an object’s properties:
var person={fname:”Bill”,lname:”Gates”,age:56};
For (x in person) // x is the attribute name {sol.log(x); } x Output fname lname age
But it’s important to note that for in is used in an array to iterate over an index
var str = ['num1'.'num2']
for(let s in str){
console.log(s);
}
1 2
Copy the code
for of
The Arrays (array)
Arrays are list-like objects. Array prototypes have various methods that allow you to manipulate them, such as modifying and traversing. The following for hand on an array… Of operation:
// array-example.js
const iterable = ['mini'.'mani'.'mo'];
for (const value of iterable) {
console.log(value);
}
// Output:
// mini
// mani
// mo
Copy the code
The result is to print out every value in the Iterable array.
Ordinary objects cannot be iterated
for… The of loop is only suitable for iteration. Ordinary objects are not iterable. Let’s take a look:
const obj = { fname: 'foo'.lname: 'bar' };
for (const value of obj) { // TypeError: obj[Symbol.iterator] is not a function
console.log(value);
}
Copy the code
Here, we define a plain object obj, and when we try for… TypeError: obj[Symbol. Iterator] is not a function TypeError: obj[Symbol. Iterator] is not a function.
We can get around this by converting array-like objects into arrays. The object will have a Length attribute, and its elements must be indexable. Let’s look at an example:
// object-example.js
const obj = { length: 3.0: 'foo'.1: 'bar'.2: 'baz' };
const array = Array.from(obj);
for (const value of array) {
console.log(value);
}
// Output:
// foo
// bar
// baz
Copy the code
The array.from () method lets me create a new instance of Array from array-like or iterable objects
Splice method and Slice method
- The splice() method modifies an array by deleting or replacing existing elements or adding new ones in place, and returns the modified contents as an array. This method changes the original array.
const months = ['Jan'.'March'.'April'.'June'];
months.splice(1.0.'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4.1.'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]
Copy the code
[Return value]
An array of deleted elements. If only one element is removed, an array containing only one element is returned. If no element is deleted, an empty array is returned.
[Delete 2 elements from bit 0 and insert “parrot”, “anemone”, and “blue”]
var myFish = ['angel'.'clown'.'trumpet'.'sturgeon'];
var removed = myFish.splice(0.2.'parrot'.'anemone'.'blue');
// myFish after calculation: [" Parrot ", "Anemone "," Blue ", "Trumpet "," Sturgeon "]
// Removed element: ["angel", "Clown "]
Copy the code
[Remove 2 elements from 2nd bit]
var myFish = ['parrot'.'anemone'.'blue'.'trumpet'.'sturgeon'];
var removed = myFish.splice(myFish.length - 3.2);
MyFish: ["parrot", "Anemone "," Sturgeon "]
// Deleted element: ["blue", "trumpet"]
Copy the code
[Delete 1 element from last to last]
var myFish = ['angel'.'clown'.'mandarin'.'sturgeon'];
var removed = myFish.splice(-2.1);
// myFish: ["angel", "Clown "," Sturgeon "]
// Deleted element: ["mandarin"]
Copy the code
[Remove all elements starting with bit 2]
var myFish = ['angel'.'clown'.'mandarin'.'sturgeon'];
var removed = myFish.splice(2);
// myFish: ["angel", "Clown "]
// Deleted element: ["mandarin", "sturgeon"]
Copy the code
- slice()The new array object () method returns a new array object
begin
和end
Determines the original arrayShallow copy(includingbegin
, not includingend
). The original array will not be changed. Remember that the shallow copy is only the first deep copy,
const animals = ['ant'.'bison'.'camel'.'duck'.'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2.4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1.5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
Copy the code
[Returns part of an existing array]
// Slice does not alter the original array
var fruits = ['Banana'.'Orange'.'Lemon'.'Apple'.'Mango'];
var citrus = fruits.slice(1.3);
// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']
Copy the code
-
The question about slice being a layer 1 deep copy
const originArray = [1.2.3.4.5]; const cloneArray = originArray.slice(); console.log(cloneArray === originArray); // false cloneArray.push(6); / / [6] // Add to the copied array without changing the original array console.log(originArray); [1.2.3.4.5]; Copy the code
Similarly, let’s try a multi-tiered array.
const originArray = [1[1.2.3] and {a:1}]; const cloneArray = originArray.slice(); console.log(cloneArray === originArray); // false cloneArray[1].push(4); cloneArray[2].a = 2; // As you can see, only the 1 of the first layer is a deep copy, but for the multilayer array [1,2,3] and object {a: 1}, it only copies the reference address, so after changing the clone, the original data will also change console.log(originArray); / / [1, 1, 2, 3, 4, 2} {a:] Copy the code
3. Join method
The **join()** method joins all the elements of an array (or an array-like object) into a string and returns the string. If the array has only one item, that item is returned without a delimiter.
[syntax]
arr.join([separator])
Copy the code
parameter
-
The separator optional
Specifies a string to delimit each element of the array. Convert the delimiter to a string if necessary. If default, array elements are separated by commas (,). If separator is an empty string (“”), there are no characters between all elements.
-
The return value
A string with all array elements concatenated. If arr.length is 0, an empty string is returned.
[description]
All array elements are converted to strings, which are concatenated with a delimiter.
If an element is undefined or null, it is converted to an empty string.
[example]
[Concatenate array elements using four different delimiters]
The following example first creates an array A with three elements, and then concatenates all the array elements with four different delimiters. First is the default comma delimiter, then a comma followed by a space, then a plus sign followed by a space, and finally an empty string.
var a = ['Wind', 'Rain', 'Fire']; var myVar1 = a.join(); // myVar1 = "Wind,Rain,Fire" var myVar2 = a.join(', '); // myVar2 = "Wind, Rain, Fire" var myVar3 = a.jin (' + '); // myVar3 = "Wind + Rain + Fire" var myVar4 = a.join("); // myVar4 changes to "WindRainFire"Copy the code
[Concatenate array object]
The following example joins class Array objects (arguments) by calling function.prototype. call on array.prototype. join.
function f(a, b, c) {
var s = Array.prototype.join.call(arguments);
console.log(s); // '1,a,true'
}
f(1, 'a', true);
Copy the code
4, the Object. The assign ()
The ** object.assign ()** method is used to assign the values of all enumerable properties from one or more source objects to target objects. It will return the target object.
grammar
Object.assign(target, ... sources)Copy the code
parameter
-
target
Target object.
-
sources
The source object.
The return value
Target object.
describe
If an attribute in the target object has the same key, the attribute is overwritten by an attribute in the source object. Properties of subsequent source objects similarly override properties of previous source objects.
The object. assign method copies only the enumerable properties of the source Object itself to the target Object. This method uses the source object’s [[Get]] and the target object’s [[Set]], so it calls the relevant getter and setter. Therefore, it assigns attributes, rather than just copying or defining new attributes. If the merge source contains getters, this may make it unsuitable to merge the new properties into the stereotype. To defined properties (including its enumerable) is copied to the prototype, the Object should be used. The getOwnPropertyDescriptor () and Object. The defineProperty ().
Both String and Symbol attributes are copied.
In the event of an error, for example, TypeError is raised if the property is not writable, and the target object can be changed if any properties are added before the error is raised.
The sample
Copy an object
const obj = { a: 1 };
const copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
Copy the code
Deep copy problem
For deep copies, an alternative approach is needed because object.assign () copies (enumerable) property values.
If the source value is a reference to an object, it simply copies its reference value.
const log = console.log;
function test() {
'use strict';
let obj1 = { a: 0 , b: { c: 0}};
let obj2 = Object.assign({}, obj1);
log(JSON.stringify(obj2));
// { a: 0, b: { c: 0}}
obj1.a = 1;
log(JSON.stringify(obj1));
// { a: 1, b: { c: 0}}
log(JSON.stringify(obj2));
// { a: 0, b: { c: 0}}
obj2.a = 2;
log(JSON.stringify(obj1));
// { a: 1, b: { c: 0}}
log(JSON.stringify(obj2));
// { a: 2, b: { c: 0}}
obj2.b.c = 3;
log(JSON.stringify(obj1));
// { a: 1, b: { c: 3}}
log(JSON.stringify(obj2));
// { a: 2, b: { c: 3}}
// Deep Clone
obj1 = { a: 0 , b: { c: 0}};
let obj3 = JSON.parse(JSON.stringify(obj1));
obj1.a = 4;
obj1.b.c = 4;
log(JSON.stringify(obj3));
// { a: 0, b: { c: 0}}
}
test();
Copy the code
Merge objects
const o1 = { a: 1 }; const o2 = { b: 2 }; const o3 = { c: 3 }; const obj = Object.assign(o1, o2, o3); console.log(obj); // { a: 1, b: 2, c: 3 } console.log(o1); // {a: 1, b: 2, c: 3}, note that the target object itself also changes.Copy the code
Merge objects with the same properties
const o1 = { a: 1, b: 1, c: 1 };
const o2 = { b: 2, c: 2 };
const o3 = { c: 3 };
const obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
Copy the code
Property is overwritten by other objects with the same property in subsequent parameters.
Copy the property of type symbol
const o1 = { a: 1 };
const o2 = { [Symbol('foo')]: 2 };
const obj = Object.assign({}, o1, o2);
console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox)
Object.getOwnPropertySymbols(obj); // [Symbol(foo)]
Copy the code
Inherited properties and non-enumerable properties cannot be copied
Const obj = object.create ({foo: 1}, {// foo is an inherited property. Bar: {value: 2 // bar is a non-enumerable property. }, baz: {value: 3, enumerable: true // Baz is a self-enumerable property. }}); const copy = Object.assign({}, obj); console.log(copy); // { baz: 3 }Copy the code
Primitive types are wrapped as objects
const v1 = "abc"; const v2 = true; const v3 = 10; const v4 = Symbol("foo") const obj = Object.assign({}, v1, null, v2, undefined, v3, v4); // Primitive types are wrapped, null and undefined are ignored. // Note that only string wrapping objects can have their own enumerable properties. console.log(obj); // { "0": "a", "1": "b", "2": "c" }Copy the code
5. Push, unshift
1. Push (), pop() and unshift(), shift()
Connection: Both groups operate on an array and change the length and contents of the array itself.
The difference is that push() and pop() add and subtract from the end of the array, while unshift() and shift() add and subtract from the end of the array.
var arr = [1.2];
Copy the code
2. Push () and unshift()
Add several elements * to the end/head of the array and return the new length of the array; The return value is the new length of the array
arr.push(3.4);// return the new length of arr 4
arr ; / / arr = [1, 2, 3, 4];
arr.unshift(0.0.5); // Return the new length of arr 6
arr ; ,0.5 / / arr = [0, 1, 2, 3, 4].
Copy the code
3. Pop () and Shift ()
Removes one element (and only one)* from the end/head * of the array and returns the deleted element; Empty arrays continue to be deleted without error, but return undefined;
arr.pop();// return 4;arr ;,0.5 / / arr = [0, 1, 2, 3].arr.pop();// return 3;arr ;,0.5 / / arr = [0, 1, 2];Arr. Shift ();// return 0;arr ;/ / arr = [0.5, 1, 2]
Copy the code
PS: pop() and shift() do not accept arguments.
arr.pop(3);// return 2; Always return the last one;arr ;/ / arr = [0.5, 1];
arr.shift(1);/ / return 0.5; Always return the first;arr ;// arr = [1];arr.pop() ;// return 1;arr ;// arr = [];arr.shift()// return undefined;arr ;// arr = [];
Copy the code
Note: The unshift method alters the original index of the array
Js variable promotion, this, new
Js superclassic interview question foo.getName (
Here is a super classic JS interview question. It contains static properties and instance properties, variable promotion, this refers to the process of new a function
function Foo() {
getName = function () {
console.log(1);
};
return this;
};
Foo.getName = function () {
console.log(2);
};
Foo.prototype.getName = function () {
console.log(3);
};
var getName = function () {
console.log(4);
};
function getName() {
console.log(5);
};
Foo.getName();
getName();
Foo().getName();
getName();
new Foo.getName();
new Foo().getName();
new newFoo().getName(); Copy the codeCopy the code
Let me print the result
Foo.getName(); / / 2
getName(); / / 4
Foo().getName(); / / 1
getName(); / / 1
new Foo.getName(); / / 2
new Foo().getName(); / / 3
new new Foo().getName(); / / 3Copy the codeCopy the code
1. foo.getName ()
We first define a function called Foo, then create a static property called getName to store an anonymous function for Foo, and then create a new anonymous function called getName for Foo’s prototype object. We then create a function called getName using function variable expressions, and finally declare a function called getName.
The foo. getName of the first question is, of course, accessing a static property stored on the Foo function, which is, of course, 2
2. GetName ()
Why is the output 4? Here is the variable promotion and function declaration promotion. If a variable is used before it is declared, it will not raise the value of the variable.
console.log(a)// undefined
var a = 1;
console.log(a)/ / 1Copy the codeCopy the code
Because the declaration advance pushes the declaration up to the top of the code, and the assignment stays in place, the above code is equivalent to:
var a
console.log(a)// undefined
a = 1;
console.log(a)/ / 1Copy the codeCopy the code
Function declarations can also be declared ahead of time, i.e. we can call the function before it is declared:
fn() / / 1
function fn() {
console.log(1);
};
fn() / / 1
// Because the function declaration is advanced, the function declaration will also be pushed to the top of the code, so it is equivalent to
function fn() {
console.log(1);
};
fn() / / 1
fn() / / 1Copy the codeCopy the code
So there’s a problem, variable declarations get promoted, function declarations get promoted, and who gets promoted more? JavaScript explicitly states that function declarations are promoted first, that is, both are promoted, but functions are promoted more than variables, so the order of the two functions in the question can be rewritten as:
function getName() {
console.log(5);
};
var getName;
getName = function () {
console.log(4); }; Copy the codeCopy the code
So that explains why it’s output 4.
3.Foo().getName()
Actually can see, we are executing Foo () function when getName this variable ascension to the outside of the global scope, because in js, if for a variable doesn’t use var or let statement, he is the default global properties, a property is the window object. So in this case our global getName is changed again because Foo() returns this and this is the window object and what we need to know is that in the browser all global declarations are properties and methods of the window object, So here we call this.getName() and it returns 1.
4. GetName ()
In the previous analysis, the value of getName was changed when Foo was executed, so another call to getName is the same as window.getName(), which also outputs 1.
5.new foo.getName ()
[new Foo() > Foo() > new Foo] [Foo. GetName () = 2] [Foo. New Foo. GetName: Foo. GetName: Foo. GetName: Foo.
6. New Foo().getName()
The first step is to get an instance of new Foo(), and the second step is to use the instance’s getName method.
We know that the new process of a constructor is roughly, to create an object constructor prototype (inherit the prototype chain), calls the constructor and put this point to the new object, so that the constructor object inheritance constructor property, if there is no manual constructor returns an object, it returns the new object.
Foo. Prototype sets a getName method (the one that prints 3), so this object can be accessed from the prototype. Foo. Prototype sets a getName method (the one that prints 3), and Foo has no constructor properties. It returns a this (this refers to the instance), so this is still the same as the object we created in the prototype Foo in the previous concept. You can try to output this instance, except that the prototype has a getName method with no other attributes, so it prints 3.
7. New new Foo().getName()
New (new Foo().getName()); new Foo().getName(); The results of 3
Js to the square root
Math.h pow (3, 2); The square of 3
Math. Pow (2, 3); 2 cubic
Square root math.sqrt (value)
Such as:
Math.sqrt(9); The square root of 9 returns 3
8. How to obtain the properties of JS objects
Js uses the object attribute name to get the important points of the attribute value
1. Cannot be a variable
var obj = {};
obj.AttrName = 'Tom'
Copy the code
Note: by object. Attribute name When fetching an attribute value, the attribute name (AttrName) cannot be a variable.
2. Can be variables
Raw data array:
var rawDataList =
[
{
"countDate": "2018-04-08"."countNum": "2"
},
{
"countDate": "2018-04-18"."countNum": "2"
},
{
"countDate": "2018-04-23"."countNum": "Seven"}]Copy the code
Processing the above data:
function Day2Mon2Year(dataList,prop){
for(var i = 0; i < dataList.length; i++){
var obj = rawDataList[i]
TypeError: Cannot read property 'replace' of undefined
var dateAttr = obj.prop
// No error: Prop is a variable and cannot be fetched through. The attribute name
var dateAttr = obj[prop]
}
}
Uncaught TypeError: Cannot read property 'replace' of undefined
Day2Mon2Year.(rawDataList,'countDate');
Copy the code
3. Summary:
The following is the key, generally directly with the second way
If the attribute name is a constant (fixed value), you can obtain the value of the attribute by:
Object. Property name
Object [attribute name]
2. If the attribute name is a variable (with no fixed value), the method of obtaining the attribute value can only be:
Object [attribute name]
9. Use settimeout in Promise
Use of setTimeout in Promise
function getData() {
return new Promise((resolve, reject) = > {
setTimeout(resolve('hello'), 2000)
})
}
getData().then(res= > {
console.log(res)
})
// Immediately print hello
Copy the code
// code2
function getData() {
return new Promise((resolve, reject) = > {
setTimeout(resolve, 2000.'hello')
})
}
getData().then(res= > {
console.log(res)
})
// output hello after 2s
Copy the code
The first argument to setTimeout is func. Using func() is equivalent to returning the first argument.
This should be a function func. If you pass func(), the code parser will execute this function immediately without delay.
A common usage scenario is implementing a sleep function
// Execute the code after 1s
const sleep = (time) = > {
return new Promise(resolve= > setTimeout(resolve, time))
}
sleep(1000).then(() = > {
// Write your operation here
})
Copy the code
// Code delay
const sleep = (time) = > {
return new Promise(resolve= > setTimeout(resolve, time))
}
async function sleepAsync() {
console.log('1')
let res = await sleep(1000)
console.log('2')
return res
}
sleepAsync()
Copy the code
10. The difference between the Hash and History modes of front-end framework routing implementation
Reference juejin. Cn/post / 684490…
- During the interview, I had prepared the two ways of realizing routes and their differences in the front-end framework, but I didn’t make special efforts to understand them thoroughly at that time, so I searched others’ summaries on the Internet and temporarily held them. But it turns out, come out to mix, always, in the interview later met again, and ask the more in-depth, only by rote learning knowledge is always forget quickly, what others summary ultimately others online, given that people summarize the contents of the online a bit chaotic, decided to oneself in the summary record, to deepen our impression.
What is front-end routing
- The concept of routing comes from the server side. In SPA (single-page application), routing describes the mapping relationship between URL and function. That is, when you enter a URL in the browser, the corresponding controller will parse the submitted request, and then match the route to find the corresponding module and function for execution.
Two, how to achieve
- The two core implementation issues are how to detect route changes and how to change the URL without refreshing the page. There are usually two implementation modes, one is Hash mode and the other is History mode.
3. Hash mode
-
Early implementations of front-end routing were based on location.hash, where the value of location.hash was the content after # in the URL. The idea was to listen for the content after # to make Ajax requests for local updates without refreshing the entire page.
-
The hashchange event is used to listen for CHANGES in the URL. It is triggered when the URL is changed by browsers moving forward or backward, by tags changing the URL, or by window.location changing the URL.
The advantages and disadvantages
-
Compatible with older browsers, Angular1.x and Vue use hash routing by default
-
Only the content before the # symbol is included in the request and sent to the back end, meaning that the back end does not return a 404 error even if it does not have full routing coverage
-
Changes in the hash value add a record to the browser’s access history, so you can use the browser’s back and forward buttons to control hash switching
-
Overrides the ability of the anchor location element
-
It is not very beautiful. There will be problems if the data transmitted after the # is complex
Iv. History mode
-
History provides pushState and replaceState methods to record the state of the route, which change the URL without causing a page refresh
-
History provides a popState event similar to the Hashchange event, but the popState event is a little different: A POPState event is triggered when a URL is changed forward or backward by the browser. A POPState event is not triggered when a URL is changed via pushState/replaceState or tags. Fortunately, we can intercept calls to pushState/replaceState and tags to detect URL changes, so listening for URL changes is possible, but not as convenient as hashchange.
-
PushState (state, title, url) and replaceState(state, title, url) both accept the same three arguments:
-
State: Data that needs to be saved. This data can be retrieved in event.state when the popState event is triggered
-
Title: title, basically useless, usually pass null
-
Url: Set the URL for the new history. The origin of the new URL and the current URL must be the same. Otherwise, errors may occur.
The advantages and disadvantages
-
Simple to use, more beautiful
-
PushState () sets the new URL to be any URL of the same origin as the current URL, and the hash can only change the content after the #, so it can only set the same document URL as the current URL
-
A URL set by pushState() that is exactly the same as the current URL is also added to the history stack, and the content after hash# must be modified to be added to the new stack
-
PushState () can add any type of data to a record with the stateObject argument, whereas hash can only add short strings
-
PushState () sets the title property in addition for later use
-
The URL of the front end must be the same as the URL of the back end; otherwise, a 404 error will be reported
-
Older browsers have compatibility line issues due to the History API
11, vue
The difference between the route
A,
The router is an instance of the VueRouter, which is equivalent to a global router object, with many attributes and subobjects, such as the history object… This.$router. Push is the same as router-link.
This.$router.push adds a new record to the history stack. Detailed see vue router.vuejs.org/zh/guide/es official document…
Route is the route object that is being jumped. Get name,path,params,query, etc.
Print this. Route and this. Route and this. Route and this.
Route parameter transmission mode
1. You can write a full path by hand:
this.router.push({path:`/user/{userId}`})
If the parameter is passed in this way, you need to add the parameter path: user/ : userId to the path during route configuration.
This.$route.params.userid.
2. Can also be passed with params:
3. We can also use query to pass:
Query n is passed for PATH and params is passed for name. The way parameters are received is pretty much the same. Enclosing the route. The query. And enclosing the route. The query. And enclosing the route. The query. And enclosing the route. The params.
Note that this is just a jump to the URL, to which component the URL displays, you have to configure the route. Router jumps and label jumps have similar rules.
Words on display:
12, Three points in JS (…)
Three points (…) The real name extension operator, a new addition to ES6, can be used to expand array expressions or strings syntactically during function calls/array constructs; You can also expand object expressions in key-value mode when constructing literal objects
Literals usually refer to [1,2,3] or {name:’chuichui’} in a neat way, while multiple nested arrays and objects with three points are useless
To put it bluntly, take off your clothes, be it curly braces ([]) or curly braces ({}).
Var number = [1,2,3,4,5,6] console.log(... Var man = {name:'chuichui',height:176} console.log({... man}) / {name:'chuichui',height:176}Copy the code
What’s the use?
Its use is so widespread that we can see it everywhere. Here are a few common examples
Copy with it
// Copy the array
var arr1 = ['hello']
var arr2 =[...arr1]
arr2 // ['hello']
// Copy the object
var obj1 = {name:'chuichui'}
varobj2 ={... arr} ob12// {name:'chuichui'}
Copy the code
Combined with it
// Array merge
var arr1 = ['hello']
var arr2 =['chuichui']
var mergeArr = [...arr1,...arr2]
mergeArr // ['hello','chuichui']
// Merge objects
var obj1 = {name:'chuichui'}
var obj2 = {height:176}
varmergeObj = {... obj1,... obj2} mergeObj// {name: "chuichui", height: 176}
Copy the code
Character to array use it
var arr1 = [...'hello']
arr1 // ["h", "e", "l", "l", "o"]
Copy the code
Function arguments use it
Can be combined with normal functions, flexible use
function f(v,w,x,y,z){}var args = [2.3]
f(1. args,4. [5])
Copy the code
Use this when we want to iterate over elements in an array as function parameters!
function f(x,y,z){}
var args = [1.2.3] f(... args)// The previous method
f.apply(null,args);
Copy the code
13, js data types (typeof, instanceof)
The data type
The latest ECMAScript standard defines nine data types:
- Six primitive types, checked using the Typeof operator:
- undefined:
typeof instance === "undefined"
- Boolean:
typeof instance === "boolean"
- Number:
typeof instance === "number"
- String:
typeof instance === "string
- BigInt:
typeof instance === "bigint"
- Symbol :
typeof instance === "symbol"
- undefined:
- null:
typeof instance === "object"
. - Object:
typeof instance === "object"
. anyconstructedThe special non-data structure type of an object instance, also used as a data structure: newObject, newArray, newMap, newSet, newWeakMap, newWeakSet, newDate, and almost everything goes throughnew keywordSomething to create. - Function: non-data structure, although typeof operations result in:
typeof instance === "function"
. This result is a special abbreviation for Function, although each Function constructor is derived from the Object constructor.
Remember that the sole purpose of the Typeof operator is to check data types, and if we want to check any structural types derived from Object, using Typeof won’t work because we always get “Object”. An appropriate way to check an Object class is to use the instanceof keyword. But even that is a margin of error.
Basic type (single type) : Except Object. String, Number, Boolean, null, undefined.
Reference type: object. It contains function, Array, and Date.
JS data types: What are typeof outputs in JS?
{} and [] output object. That is, array objects are called objects
Console.log () prints function.
A method to detect array types
① The instanceof operator
③ array.isarray () checks whether the value is an Array
Typeof already has some formats
The typeof operator returns a string representing the typeof the unevaluated operand.
The following table summarizes possible typeof return values. For more information about types and raw values, see the JavaScript Data Structure page.
type | The results of |
---|---|
Undefined | "undefined" |
Null | "object" (seebelow) |
Boolean | "boolean" |
Number | "number" |
BigInt(New in ECMAScript 2020) | "bigint" |
String | "string" |
Symbol(New in ECMAScript 2015) | "symbol" |
Host object (provided by the JS environment) | It depends on the implementation |
FunctionObject (implemented according to the ECMA-262 specification [[Call]]) | "function" |
Any other object | "object" |
It is important to note that typeof returns and judgment values are lowercase and enclosed in double quotes
The instance
/ / values
typeof 37= = ='number';
/ / string
typeof ' '= = ='string';
typeof 'bla'= = ='string';
/ / a Boolean value
typeof true= = ='boolean';
// Symbols
typeof Symbol() = = ='symbol';
// Undefined
typeof undefined= = ='undefined';
/ / object
typeof {a: 1} = = ='object';
/ / function
typeof function() = = = {}'function';
typeof class C = = = {}'function'
typeof Math.sin === 'function';
Copy the code