1. How many data types does JavaScript have?
number:数字类型
string:字符串类型
boolean:布尔值类型
undefined:未定义类型
null:空类型
object:对象类型
symbol:symbol类型
bigint:大数字类型
2, JavaScript maximum safe number and minimum safe number?
console.log(Number.MAX_SAFE_INTEGER)
// 9007199254740991
console.log(Number.MIN_SAFE_INTEGER)
// -9007199254740991
3. What is the difference between deep copy and shallow copy?
浅拷贝:只拷贝第一层,深层的依然是引用,改变深层会影响原对象
深拷贝:每一层都拷贝了,改变数据不会影响原对象
4. What is a closure?
闭包是一个函数,是一个能让外部访问到函数内部的函数
优点:使外部能访问内部,延长内部变量寿命
缺点:滥用闭包造成内存泄漏
example:
function a () {
let num = 0
// 这是个闭包
return function () {
return ++num
}
}
const b = a()
console.log(b()) // 1
console.log(b()) // 2
5. What is the prototype chain
原型链是一条引用的链,实例的隐式原型指向构造函数的显式原型,可以使用A instanceof B来判断B是否在A的原型链上。
6. What is variable promotion? Function promotion?
variable promotion
console.log(name) // undefined
var name = 'Sunshine_Lin'
if (false) {
var age = 23
}
console.log(age) // undefined 不会报错
function hoisting
console.log(fun) // function fun() {}
function fun() {}
if (false) {
function fun2(){}
}
console.log(fun2) // undefined 不会报错
Function Promotion Priority > Variable Promotion Priority
console.log(fun) // function fun() {}
var fun = 'Sunshie_Lin'
function fun() {}
console.log(fun) // 'Sunshie_Lin'
7. What is the difference between isNaN and Number.isNaN?
isNaN:除了判断NaN为true外,还会把不能转成数字判断为true,例如'dasd'
Number.isNaN:只会判断NaN为true
8. When solving the problem of traversing the object, what should I do if the properties on the prototype are traversed?
Use hasOwnProperty to judge
function Person(name) {
this.name = name
}
Person.prototype.age = 23
const person = new Person('Sunshine_lin')
for (const key in person) { console.log(key) } // name age
// 使用 hasOwnProperty
for (const key in person) {
person.hasOwnProperty(key) && console.log(key)
} // name
9, valueOf and toString?
valueOf比较偏向于计算,toString偏向于显示
对象转换时,优先调用toString
强转字符串时优先调用toString,强转数字时优先调用valueOf
正常情况下,优先调用toString
运算操作符情况下优先调用valueOf
10. What is the specific storage form of JavaScript variables in memory?
基本数据类型:存在栈内存里
引用数据类型:指针存栈内存,指向堆内存中一块地址,内容存在堆内存中
11. Tell me about the boxing and unboxing of JavaScript?
Boxing: The operation of converting a primitive data type into a corresponding reference data type
Look at the following code, s1 is just a basic data type, how can he call indexOf?
const s1 = 'Sunshine_Lin'
const index = s1.indexOf('_')
console.log(index) // 8
It turns out that the boxing operation is performed inside JavaScript
1. Create an instance of the String type;
2. Call the specified method on the instance;
3. Destroy the instance;
var temp = new String('Sunshine_Lin')
const index = temp.indexOf('_')
temp = null
console.log(index) // 8
Unboxing: The operation of converting a reference data type to the corresponding basic data type
Implement unboxing operations through valueOf or toString methods
var objNum = new Number(123);
var objStr =new String("123");
console.log( typeof objNum ); //object
console.log( typeof objStr ); //object
console.log( typeof objNum.valueOf() ); //number
console.log( typeof objStr.valueOf() ); //string
console.log( typeof objNum.toString() ); // string
console.log( typeof objStr.toString() ); // string
12. What are the similarities and differences between null and undefined?
相同点
1、都是空类型
2、转布尔值都是false,都是假值
3、null == undefined 为 true
不同点
1、typeof,前者为object,后者为undefined
2、null转数字为0,undefined转数字为NaN
3、null === undefined 为 false
13. How to judge the data type?
typeof:能判断string、number、undefined、boolean、function、object(null是object)
Object.prototype.toString.call():能判断大部分数据类型
instanceOf
14. Why is typeof null object?
不同数据类型底层都是用二进制来表示的,二进制前三位为000则会被判断为object,而null二进制全是0,所以被判断成object
15. What is the difference between == and ===?
==:比较过程会进行隐式转换
===:值相同,类型相同才会为true
16. Implicit conversion rules in JavaScript?
转string类型:+(字符串连接符)
转number类型:++/--(自增自减运算符) + - * / %(算术运算符) > < >= <= == != === !== (关系运算符)
转boolean:!(逻辑非运算符)
17. What are the conversion rules for the left and right sides of the double equals sign?
1、null == undefined 为 true
2、如果有一个操作数是布尔值,则在比较相等性之前先将其转换为数值——false转换为0,而true转换为1;
3、如果一个操作数是字符串,另一个操作数是数值,在比较相等性之前先将字符串转换为数值
4、如果一个操作数是对象,另一个操作数不是,则调用对象的toString()方法,用得到的基本类型值按照前面的规则进行比较
18. Why is undefined >= undefined false?
隐式转换,变成NaN >= NaN,NaN不等于自身也不大于自身
19. Why is null >= null true?
隐式转换,变成0 >= 0,为true
20. Why is [] == ![] true?
第一步:转为[] == false
第二步:转为[] == 0
第三步:转为'' == 0
第四步:转为0 == 0
21. 0.1 + 0.2 === 0.3, right?
不对,JavaScript存在精度丢失问题,由于有些小数无法用二进制表示,所以只能取近似值,解决方法有:
先转大数,再变小数
使用toFixed
22. What is an anonymous function?
An anonymous function is a function without a name, such as:
(function(x, y){
alert(x + y);
})(2, 3)
23. How many ways are there to bind click events?
三种
xxx.onclick = function (){}
<xxx onclick=""></xxx>
xxx.addEventListener('click', function(){}, false)
24. What is the third parameter of addEventListener?
决定事件是捕获阶段执行还是冒泡阶段执行
true:捕获
false:默认,冒泡
25. What is the difference between a function declaration and a function expression?
Function declaration: enjoy function hoisting function expression: classified in variable declaration, enjoy variable hoisting function hoisting priority > variable hoisting priority
console.log(fun) // fun () {}
// 函数表达式
var fun = function(name) {}
// 函数声明
function fun () {}
console.log(fun) // fun (name) {}
26. What are the event flow models of JavaScript?
事件冒泡:由最具体的元素接收,并往上传播
事件捕获:由最不具体的元素接收,并往下传播
DOM事件流:事件捕获 -> 目标阶段 -> 事件冒泡
27. What is the difference between Ajax, Axios, and Fetch?
Ajax:是对XMLHttpRequest(XHR)的封装
Axios:是基于Promise对XHR对象的封装
Fetch:是window的一个方法,基于Promise,与XHR无关,不兼容IE
28. What is the difference between load, $(document).ready, and DOMContentLoaded?
$(document).ready、DOMContentLoaded:DOM树构建完毕,但还没有请求静态资源
load:静态资源请求完毕
29. How to prevent event bubbling?
function stopBubble(e) {
if (e.stopPropagation) {
e.stopPropagation()
} else {
window.event.cancelBubble = true;
}
}
30. How to prevent the default behavior of events?
function stopDefault(e) {
if (e.preventDefault) {
e.preventDefault();
} else {
window.event.returnValue = false;
}
}
31. What is event delegation?
当子元素都需要绑定相同事件时,可以将事件绑在父元素上,优点有:
绑定在父元素,则只需绑定一次,节省性能
后续新增的子元素也可以触发父元素绑定的事件
32. How to implement array deduplication?
// 使用 Map 去重
function quchong1(arr) {
const newArr = []
arr.reduce((pre, next) => {
if (!pre.get(next)) {
pre.set(next, 1)
newArr.push(next)
}
return pre
}, new Map())
return newArr
}
// 使用 Set 去重
function quchong (arr) {
return [...new Set(arr)]
}
33. What is the difference between Set and Array?
Set使用has判断有无元素,数组使用索引
Set添加元素使用方法add,数组用push、unshift
Set长度为size,数组为length
Set会自动把同样的基础数据类型去重,数组不能
Set删除元素用delete,数组用splice、pop、shift
Set可以使用clear清空,数组需要重新赋值[]
数组可以传入new Set(array),实现数组转Set
Set可以使用keys、value方法,转数组
Set自带forEach方法进行遍历
34. What is the difference between Map and Object?
Map使用set设置属性,对象使用obj[key] = value
Map使用get获取属性值,对象使用obj[key]
Map使用has判断属性存在与否,对象只能obj[key]
Map删除元素使用delete方法,对象使用delete关键字
Map使用clear进行情空,对象需要重新赋值{}
Map和对象都可以使用entries方法转数组键值对
Map自带forEach方法进行遍历
35. What is NaN? What are the characteristics?
typeof NaN 为 number
NaN不等于自身,不大于自身,不小于自身
NaN可以使用Number.isNaN判断
NaN是假值,转布尔值为false
36. What are the methods for handling asynchrony?
回调函数
Promise
事件监听
发布订阅
async/await
37. How many inheritance methods are there in JavaScript?
Pre-work
// 定义一个动物类
function Animal (name) {
// 属性
this.name = name || 'Animal';
// 实例方法
this.sleep = function(){
console.log(this.name + '正在睡觉!');
}
}
// 原型方法
Animal.prototype.eat = function(food) {
console.log(this.name + '正在吃:' + food);
};
1. The core of prototype chain inheritance: use the instance of the parent class as the prototype of the child class
function Cat(){
}
Cat.prototype = new Animal();
Cat.prototype.name = 'cat';
var cat = new Cat();
console.log(cat.name); // cat
cat.eat('fish') // cat正在吃:fish
cat.sleep() // cat正在睡觉!
console.log(cat instanceof Animal); //true
console.log(cat instanceof Cat); //true
advantage:
1. A very pure inheritance relationship, an instance is an instance of a subclass and an instance of the parent class
2. The parent class adds prototype methods/properties, which can be accessed by subclasses
3. Simple and easy to implement
shortcoming:
1. To add properties and methods to subclasses, they must be executed after statements such as new Animal() and cannot be placed in the constructor
2. All properties from the prototype object are shared by all instances
3. When creating a child instance, you cannot pass parameters to the parent class constructor
4. Multiple inheritance is not supported
2. The core of structural inheritance: using the constructor of the parent class to enhance the subclass instance is equivalent to copying the instance attributes of the parent class to the subclass (without using the prototype)
function Cat(name) {
Animal.call(this);
this.name = name || 'Tom';
}
var cat = new Cat();
console.log(cat.name); // Tom
cat.sleep() // Tom正在睡觉!
console.log(cat instanceof Animal); // false
console.log(cat instanceof Cat); // true
advantage:
1. Solve the problem that in the prototype chain inheritance, the subclass instance shares the reference attribute of the parent class
2. When creating an instance of a subclass, you can pass parameters to the parent class
3. Multiple inheritance can be achieved (call multiple parent class objects)
shortcoming:
1. The instance is not an instance of the parent class, but an instance of the knowledge subclass
2. It can inherit the instance properties and methods of the parent class, but cannot inherit the prototype properties/methods
3. Function reuse cannot be achieved, each subclass has a copy of the parent class instance function, which affects performance
3. Instance inheritance core: add new features to parent class instances and return them as subclass instances
function Cat(name){
var instance = new Animal();
instance.name = name || 'Tom';
return instance;
}
var cat = new Cat();
console.log(cat.name) // Tom
cat.sleep() // Tom正在睡觉!
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // false
advantage:
1. There is no limit to the calling method, whether it is new subclass() or subclass(), the returned object has the same effect
shortcoming:
1. An instance is an instance of the parent class, not an instance of the child class
2. Multiple inheritance is not supported
4. Copy inheritance core: just copy one by one
function Cat(name){
var animal = new Animal();
for(var p in animal){
Cat.prototype[p] = animal[p];
}
this.name = name || 'Tom';
}
var cat = new Cat();
console.log(cat.name); // Tom
cat.sleep() // Tom正在睡觉!
console.log(cat instanceof Animal); // false
console.log(cat instanceof Cat); // true
advantage:
1. Support multiple inheritance
shortcoming:
1. Low efficiency and high memory usage (because the attributes of the parent class need to be copied)
2. Unable to obtain non-enumerable methods of parent class (non-enumerable methods cannot be accessed using for in)
5. Combination inheritance core: Construct the parent class, inherit the properties of the parent class and retain the advantages of passing parameters, and then realize function reuse by using the parent class instance as the child class prototype
function Cat(name){
Animal.call(this);
this.name = name || 'Tom';
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
var cat = new Cat();
console.log(cat.name); // Tom
cat.sleep() // Tom正在睡觉!
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // true
advantage:
1. Make up for the defects of structural inheritance, can inherit instance properties/methods, and can also inherit prototype properties/methods
2. It is both an instance of the subclass and an instance of the parent class
3. There is no reference attribute sharing problem
4. Can pass parameters
5. Functions can be reused
shortcoming:
1. The parent class constructor is called twice, and two instances are generated (the subclass instance shields the one on the subclass prototype)
6. Inheritance core of parasitic combination: cut off the instance attributes of the parent class through the parasitic method, so that when the construction of the parent class is called twice, the instance method/property will not be initialized twice, avoiding the shortcomings of inheritance combination
function Cat(name) {
Animal.call(this);
this.name = name || 'Tom';
}
// 创建一个没有实例方法的类
var Super = function () { };
Super.prototype = Animal.prototype;
//将实例作为子类的原型
Cat.prototype = new Super();
// Test Code
var cat = new Cat();
console.log(cat.name); // Tom
cat.sleep() // Tom正在睡觉!
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); //true
advantage:
1. It is perfect
shortcoming:
1. Realization is complex
38. What are the ways to create an object?
new Object
const obj = new Object()
obj.name = 'Sunshine_Lin'
literal
const obj = { name: 'Sunshin_Lin' }
factory pattern
function createObj(name) {
const obj = new Object()
obj.name = name
return obj
}
const obj = createObj('Sunshine_Lin')
Constructor
function Person(name) {
this.name = name
}
const person = new Person('Sunshine_Lin')
39. What are the four situations pointed to by this?
new operator
function Person(name) {
this.name = name
console.log(this)
}
// this指向当前person实例对象
const person = new Person('Sunshine_Lin')
point to window
function fn() {
console.log(this)
}
fn() // 浏览器window,node里global
object call method
const target = {
fn: function () { console.log(this) }
}
target.fn() // target
// 这种就是改变了this了
const fn = target.fn
fn() // 浏览器window,node里global
arrow function
const obj = {
name: '林三心',
fn: () => {
console.log(this.name)
}
}
console.log(obj.fn()) // undefined
call, apply, bind change this
const obj1 = {
name: '林三心',
sayName: function() {
console.log(this.name)
}
}
const obj2 = {
name: 'Sunshin_Lin'
}
// 改变sayName的this指向obj2
obj1.sayName.call(obj2) // Sunshin_Lin
// 改变sayName的this指向obj2
obj1.sayName.apply(obj2) // Sunshin_Lin
// 改变sayName的this指向obj2
const fn = obj1.sayName.bind(obj2)
fn() // Sunshin_Lin
40. What are the common methods of arrays?
method | effect | Whether to affect the original array |
---|---|---|
push | Add element after array, return length | ✅ |
pop | Delete the last item of the array and return the deleted item | ✅ |
shift | Delete the first item of the array and return the deleted item | ✅ |
unshift | Add an element to the beginning of the array and return the length | ✅ |
reserve | Reverse array, return array | ✅ |
sort | Sort array, return array | ✅ |
splice | Intercept the array and return the intercepted part | ✅ |
join | Convert array to string, return string | ❌ |
concat | concatenating arrays | ❌ |
map | The same rules handle array items, returning a new array | ❌ |
forEach | iterate over the array | ❌ |
filter | Filter array items and return an array that matches the condition | ❌ |
every | Returns true for each rule | ❌ |
some | Returns true as long as one item matches the rule | ❌ |
reduce | Accept the previous return and the next item in the array | ❌ |
flat | Array flattening | ❌ |
slice | Intercept the array and return the intercepted interval | ❌ |
41. What are the common methods of Math?
method | effect |
---|---|
Math.max(...arr) | take the maximum value in arr |
Math.min(...arr) | take the smallest value in arr |
Math.ceil(decimal) | round up decimals |
Math.floor(decimal) | Decimals are rounded down |
Math.round(decimal) | Decimal rounding |
Math. sqrt(num) | square num |
Math.pow(num, m) | Raise num to the power m |
Math.random() * num | Take a random number from 0-num |
42. What are the different types of popup boxes in JS?
在JS中有三种类型的弹出框可用,分别是:
Alert、Confirm、Prompt
43. How to convert JS date to ISO standard
var date = new Date();
var n = date.toISOString();
console.log(n);
// YYYY-MM-DDTHH:mm:ss.sssZ
44. How to encode and decode URLs in JS
编码:encodeURI()
解码:decodeURI()
45. What is BOM? What APIs are there?
BOM is browser object model, browser object model
api | effect | represents a method or property |
---|---|---|
window.history | Manipulate browser records | history.back(), history.go(-1) |
window.innerHeight | Get the height of the browser window | |
window.innerWidth | Get the width of the browser window | |
window.location | Action refresh button and address bar | location.host: get the domain name and port |
window.location | Action refresh button and address bar | location.hostname: get the hostname |
window.location | Action refresh button and address bar | location.port: get the port number |
window.location | Action refresh button and address bar | location.pathname: get the path of the url |
window.location | Action refresh button and address bar | location.search: get the part that starts with ? |
window.location | Action refresh button and address bar | location.href: get the entire url |
window.location | Action refresh button and address bar | location.hash: get the part starting with # |
window.location | Action refresh button and address bar | location.origin: Get the current domain name |
window.location | Action refresh button and address bar | location.navigator: Get current browser information |
46. Relationship between BOM and DOM
BOM全称Browser Object Model,即浏览器对象模型,主要处理浏览器窗口和框架。
DOM全称Document Object Model,即文档对象模型,是 HTML 和XML 的应用程序接口(API),遵循W3C 的标准,所有浏览器公共遵守的标准。
JS是通过访问BOM(Browser Object Model)对象来访问、控制、修改客户端(浏览器),由于BOM的window包含了document,window对象的属性和方法是直接可以使用而且被感知的,因此可以直接使用window对象的document属性,通过document属性就可以访问、检索、修改XHTML文档内容与结构。因为document对象又是DOM的根节点。
可以说,BOM包含了DOM(对象),浏览器提供出来给予访问的是BOM对象,从BOM对象再访问到DOM对象,从而js可以操作浏览器以及浏览器读取到的文档。
47. What is the difference between the substr() and substring() functions in JS
The substr() function is of the form substr(startIndex,length). It returns the substring from startIndex and returns the number of 'length' characters.
var s = "hello";
( s.substr(1,4) == "ello" ) // true
The substring() function is of the form substring(startIndex,endIndex). It returns the substring from startIndex to endIndex - 1.
var s = "hello";
( s.substring(1,4) == "ell" ) // true
48. Explain "use strict"?
“use strict”是Es5中引入的js指令。使用“use strict”指令的目的是强制执行严格模式下的代码。在严格模式下,咱们不能在不声明变量的情况下使用变量。早期版本的js忽略了“use strict”。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。