当前位置:网站首页>JS interview questions (I)
JS interview questions (I)
2022-07-06 13:24:00 【Famiglistimo66】
One 、JavaScript Basics
1、 Introduction to basic data types
All programming languages have the concept of data types .
stay JavaScript
in , Data types can be divided into basic data types and reference data types . The basic data types include Undefined
,Null
,Boolean
,Number
,String
5 Types . stay ES6
A basic data type is added in Symbol
.
There are Object
,Function
,Array
,Date
etc. .
problem : What is the difference between the two types ?
Different storage locations
difference | Basic data type | Reference data type |
---|---|---|
Storage location | Stack (stack) | Pile up (heap) |
Take up space | Small , Fixed size | Big , Size is not fixed |
Reference data types store pointers in the stack , The pointer points to the starting address of the entity in the heap . When the interpreter looks for a reference value , Will first retrieve its address in the stack , Get the address and get the entity from the heap .
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-gaOuN7U3-1644670612785)(images/ Basic data type and reference type .png)]
Now let's review the basic data types , Later, we will review the content of quotation type , And look at the corresponding common interview questions .
1.1 Undefined type
Undefined
Type has only one unique literal undefined
, It means that a variable does not exist .
problem : Which scenes will appear undefined
?
First of all : When using variables that are declared but not initialized , Returns the undefined
var a
console.log(a) //undefined
second : When getting a nonexistent property of an object , Returns the undefined
var obj={
userName:'zhangsan'
}
console.log(obj.age)//undefined
Third : Function has no explicit return value , But print the call result of the function
function fn(){
}
console.log(fn()) //undefined
Fourth : When defining a function , Multiple formal parameters are used , But the number of parameters passed during the call is less than the number of formal parameters , Then the parameter without matching is undefined
function fn(p1,p2,p3){
console.log(p3) //undefined
}
fn(1,2)
1.2 Null type
Null
Type has only one unique literal null
, An object that represents a null pointer , It's also in use typeof
Running symbol detection null
Value will return object
Why .
problem : Which scenes will appear null
?
First of all : In general , If the declared variable is to save a value later , It should be assigned to... At the time of declaration null
var obj=null
function foo(){
return {
userName:'zhangsan'
}
}
obj=foo();
second :JavaScript
In obtaining DOM
Element time , If the specified element object is not obtained , It will return null
document.querySelector('#id') //null
Third : When using regular expressions for matching , If there is no matching result , It will return null
'test'.match(/a/);// null
1.3 Undefined And null Compare
Undefined
and Null
Although there are two different basic data types , But there are similarities in some cases , Let's take a look at their similarities and differences .
(1) The same thing
First of all :Undefined
and Null
Both data types have only one literal , Namely undefined
and null
.
second :Undefined
and Null
The type is being converted to Boolean
Value of type , Will be converted to false
.
Third : When you need to convert them into objects , Will throw one TypeError
It's abnormal .
var a;
var b=null;
cosnole.log(a.name);//Cannot read property 'name' of undefined
cosnole.log(b.name);//Cannot read property 'name' of undefined
Fourth :Undefined
Type derived from Null
type , So under the comparison of non strict equality , The two are equal . As shown in the following code :
null==undefined //true
(2) Difference
First of all :null
yes JavaScript
Key words of , and undefined
yes JavaScript
A global variable of , That is to mount on window
A variable on the object , It's not a keyword .
second : In the use of typeof
Operator to detect ,Undefined
The value of type will return undefined
. and Null
The value of type is returned as object
typeof undefined ;//undefined
typeof null ;//object
Third : When string type conversion is required ,null
It will be converted to a string null
, and undefined
String will be converted undefined
.
undefined+" abc" //"undefined abc"
null+" abc" //"null abc"
Fourth : When converting numeric types ,undefined
Will be converted to NaN
, Unable to participate in the calculation , and null
Will be converted to 0
, Can participate in calculation .
undefined +0;// NaN
null+0 ;// 0
The fifth : Suggest : In any case, it is not necessary to assign the value of a variable display to undefined
. If you need to define a variable to save the object to be used in the future , It should be initialized to null
.
1.4 Boolean type
Boolean
type ( Boolean type ) The literal quantity of is only two , Namely true
and false
, They are case sensitive .
Boolean
The most commonly used scenario is for if
Sentence judgment . stay JavaScript
in ,if
Statement can accept any type of expression , namely if(a)
Statement a
, It can be Boolean
,Number
,String
,Object
,Null
,Undefined
Other types .
If a
No Boolean
Type value , that JavaScript
The parser will automatically call Boolean( )
Function pair a
Do type conversion , Return to the final compliance if
Sentence judgment true
Or is it false
value .
Different types and Boolean
The conversion of the value of type is Boolean
The focus of the type .
First of all :String
Type conversion to Boolean
type
Empty characters will be converted to false
, Any non empty string will be converted to true
second :Number
Type conversion to Boolean
type
0
and NaN
Will be converted to false
. Besides 0
and NaN
Everything else will change true
.
Third :Object
Type conversion Boolean
type
If object
by null
when , Will be converted to false
, If object
Not for null
, Will be converted into true
.
var obj={
}
Boolean(obj) //true
var obj=null
Boolean(obj)//false
Fourth :Function
Type conversion Boolean
type
whatever Function
The type will be converted to true
var fn=function(){
}
Boolean(fn)//true
The fifth :Null
Type conversion to Boolean
type , We know Null
There is only one type null
value , Will be converted to false
.
The sixth :Undefined
Type conversion Boolean
type , We know Undefined
There is only one type undefined
value , Will be converted to false
.
1.5 Number type
stay JavaScript
in ,Number
Type data includes integer data , Floating point data is also included .
Let's first look at the handling of integer . Integer can be decimal , It can also be expressed in octal or hexadecimal .
First of all : octal : If you want to express a value in octal , Then the first must be 0, Other bits must be 0–7 The number of , If the following number is greater than 7, It breaks the octal rule , At this time, it will be treated as a decimal number .
var num1=024
console.log(num1) //20
var num2=079
console.log(num2) //79
num1
The first is 0
For octal , Every last number is in 0--7
Between , So it conforms to octal rule , Finally, the decimal system is 20
num2
The first is also 0, But the last one has surpassed 7, So it doesn't belong to octal , Here, it is directly treated as decimal , The final output is 79.
second : Hexadecimal :
If you want to express a value in hexadecimal , Then the first two must be 0x
, The other bits must be (0–9,a--f
perhaps A--F
). If it's beyond that range , An exception will be thrown .
var num1=0x5f //95
var num2=Ox5h //Uncaught SyntaxError: Invalid or unexpected token
And Boolean
Same type , When other types are in contact with Number
Data conversion of type , Will also abide by certain rules .
1.5.1 Number Type conversion
In actual development , We often encounter converting other types of values to Number
Case of type . stay JavaScript
in , Altogether 3 Functions can complete this conversion , Namely Number()
function ,parseInt( )
function ,parseFloat( )
function . Let's take a look at the precautions for these functions .
Number( ) function
Number( )
Function can be used to convert any type to Number
type , It follows the following rules when converting :
First of all : If it's a number , According to the corresponding hexadecimal data format , Unified conversion to decimal returns .
Number(10) //10
Number(010) // 8, 010 It's octal data , The conversion to decimal is 8
Number(0x10) // 16,0x10 Is hexadecimal data , The conversion to decimal is 16
second : If it is Boolean
Type value ,true
return 1,false
Return yes 0
Number(true) //1
Number(false) //0
Third : If the value is null
, Then return to 0
Number(null) //0
Fourth : If the value is undefined
, Then return to NaN
Number(undefined) //NaN
The fifth : If the value is of string type , The following rules need to be followed
(1) If the string contains only numbers , Will be directly converted to decimal numbers ; If the number is preceded by 0, Will directly ignore this 0.
Number('21') //21
Number('012') //12
(2) If the string is a valid floating-point number , Will be directly converted to the corresponding floating-point number , The preceding multiple repeated 0 Will be deleted , Keep only one .
Number('0.12') //0.12
Number('00.12') //0.12
(3) If the string is a valid hexadecimal form , Will be converted to the corresponding decimal value
Number('0x12') //18
(4) If the string is a valid octal , Will not be converted according to octal , Instead, it is converted directly according to decimal system and output , Because the front 0 Will be directly ignored .
Number('010') //10
Number('0020') //20
(5) If the string is empty , That is, the string does not contain any characters , Or consecutive spaces , It will be converted to 0.
Number('') //0
Number(' ')//0
(6) If the string contains any discomfort above 5 Other format contents in case , Will return NaN
Number('123a') //NaN
Number('abc') //NaN
The sixth : If it's an object type , Will call the... Of the object valueOf( )
Function to get the return value , And judge whether the return value can be converted to Number
type , If not , Will call the object toString( )
Function to get the return value , And judge whether it can be converted into Number
type . If not satisfied , Then return to NaN
.
The following is through valueOf( )
Function converts an object to Number
type .
var obj={
age:'12',
valueOf:function(){
return this.age
},
}
Number(obj) //12
The following is through toString( )
Function converts an object to Number
type .
var obj={
age:'21',
toString:function(){
return this.age
}
}
Number(obj)
parseInt( ) function
parseInt()
Function is used to parse a string , And return the integer value corresponding to the specified cardinality .
Grammar format :
parseInt(string,radix)
among string
The parameter represents the value to be parsed , If the parameter is not a string , Then you can use toString( )
Function to convert it to a string . And the blank character in front of the string will be ignored .
radix
It represents the radix of base conversion , It can be binary , Decimal system , Octal and hexadecimal . The default value is 10.
Because different results may be obtained when the same number is processed with different base numbers , So in any case parseInt
Function time , It is recommended to manually supplement the second parameter .
parseInt( )
Function will return the integer value after string parsing , If the string cannot be converted to Number
type , Will return NaN
.
parseInt('aaa')//NaN
In the use of parseInt
When the function converts a string to an integer , Something to be aware of :
First of all : If the parameter passed in is of non string type , You need to convert it to string type first . Even if the incoming data is integer .
second :parseInt( )
When the function is converting , The principle of pre matching will be adopted for the incoming string .
parseInt("fg123",16)
For strings fg123
, Start with the first character ,f
Is to meet the hexadecimal data , Because the range of hexadecimal data is 0--9
,a--f
, So keep f
, Then there is the second character g
, It does not meet the hexadecimal data range , Therefore, the second character is discarded from the last character , The final string only retains characters f
, Then put the character f
Convert to hexadecimal data , by 15, Therefore, the final result returned is 15
.
Another thing to note is , If arithmetic operations are involved in the incoming string , It won't be implemented , Arithmetic symbols are treated as characters .
parseInt('16*2')// 16, Here, it is directly treated as a string , Does not perform multiplication
parseInt(16*2) // 32
Third : Dealing with floating point numbers
If the value passed in is a floating point number , The decimal point and the number after it will be ignored , Round directly .
parseInt(12.98) //12
Fourth :map( )
Function and parseInt( )
Function problem
Let's assume a scenario , There is an array , Every element in the array is a numeric string ,[‘1’,‘2’,‘3’,‘4’], If you convert all the elements in this array to integers , How to deal with it ?
Here we may think of using map( )
function , Then call... In this function parseInt( )
Function to complete the conversion . So the code is as follows :
<script>
var arr = ["1", "2", "3", "4"];
var result = arr.map(parseInt);
console.log(result);
</script>
The result of executing the above procedure is :[1,NaN,NaN,NaN]
Why does this happen ?
The above code is equivalent to the following code
var arr = ["1", "2", "3", "4"];
// var result = arr.map(parseInt);
var result = arr.map(function (val, index) {
return parseInt(val, index);
});
console.log(result);
Through the above code , You can find ,parseInt
The second parameter of the function is actually the index value of the array . therefore , The overall form is as follows :
parseInt('1',0) // Any integer in 0 When rounding the radix , Will return to itself , So what's going back here is 1
parseInt('2',1) // Be careful parseInt The value range of the second parameter is 2--36, So it doesn't meet the conditions , You can only go back here NaN
parseInt('3',2) // It means that you will 3 Process as binary , But binary only has 0 and 1, therefore 3 Out of range , Unable to convert , return `NaN`
parseInt('4',3) // take 4 Treat as ternary , however 4 Cannot be represented by ternary data , return NaN
So when we were map( )
Use in a function parseInt( )
Function time , Can't directly parseInt( )
Function as map( )
The parameters of the function , It needs to be map( )
Function in the callback function , And try to specify the cardinality . The code is as follows :
var arr = ["1", "2", "3", "4"];
var result = arr.map(function (val) {
return parseInt(val, 10);
});
console.log(result);
边栏推荐
- Alibaba cloud microservices (III) sentinel open source flow control fuse degradation component
- 西安电子科技大学22学年上学期《基础实验》试题及答案
- View UI Plus 发布 1.2.0 版本,新增 Image、Skeleton、Typography组件
- Inheritance and polymorphism (Part 2)
- String class
- Music playback (toggle & playerprefs)
- Voir ui plus version 1.3.1 pour améliorer l'expérience Typescript
- Redis介绍与使用
- CorelDRAW plug-in -- GMS plug-in development -- Introduction to VBA -- GMS plug-in installation -- Security -- macro Manager -- CDR plug-in (I)
- Set container
猜你喜欢
There is always one of the eight computer operations that you can't learn programming
System design learning (III) design Amazon's sales rank by category feature
图书管理系统小练习
TYUT太原理工大学2022数据库大题之E-R图转关系模式
9.指针(上)
TYUT太原理工大学2022数据库大题之分解关系模式
Database operation of tyut Taiyuan University of technology 2022 database
TYUT太原理工大学2022数据库大题之概念模型设计
String class
西安电子科技大学22学年上学期《信号与系统》试题及答案
随机推荐
阿里云微服务(一)服务注册中心Nacos以及REST Template和Feign Client
TYUT太原理工大学2022数据库大题之分解关系模式
继承和多态(下)
系统设计学习(一)Design Pastebin.com (or Bit.ly)
Record: I accidentally wrote a recursion next time
西安电子科技大学22学年上学期《基础实验》试题及答案
(超详细二)onenet数据可视化详解,如何用截取数据流绘图
几道高频的JVM面试题
How to ensure data consistency between MySQL and redis?
Set container
121道分布式面试题和答案
Rich Shenzhen people and renting Shenzhen people
TYUT太原理工大学2022软工导论简答题
Counter attack of flour dregs: redis series 52 questions, 30000 words + 80 pictures in detail.
Network layer 7 protocol
Inheritance and polymorphism (Part 2)
FileInputStream和BufferedInputStream的比较
学编程的八大电脑操作,总有一款你不会
十分钟彻底掌握缓存击穿、缓存穿透、缓存雪崩
IPv6 experiment