JS common interview questions (2)

Front-end interview question bank ( necessary for interview) recommendation: ★★★★★            

Address: front-end interview question bank

Receive National Day avatar   [National Day avatar] - National Day patriotic programmer avatar! always one option fit for you!

I sorted out some basic knowledge commonly used in js. If you have any questions, please correct me~

1. Data type

basic data type reference data type Compare
String Object Essential difference:
basic data types and reference data types have different storage methods in memory.
The basic data type is a simple data segment directly stored in the stack, which occupies a small space and belongs to frequently used data.
Reference data types are stored in heap memory and occupy a large space. The reference data type stores a pointer on the stack, which points to the starting address of the entity in the heap. When the interpreter looks for the reference value, it will retrieve its address in the stack, and obtain the entity from the heap after obtaining the address.
Number Array
Boolean Function
Null Regexp
Undefined Date
Symbol Math

Two, typeof

typeof is an operator, there are two ways to use it: typeof (expression) and typeof variable name, the first is to operate on expressions, and the second is to operate on variables

return value:

type of data return type
Null Object
Object Object
Function Object
Number Number
String String
void(0) undefined
void() SyntaxError
undefined undefined
Symbol('a') Symbol

3. Arrow functions and ordinary functions

arrow function Ordinary function
anonymous function Can be an anonymous function or a named function
Cannot be used as a constructor, cannot use the new keyword
No yuan prototype, that is, no prototype attribute
call, apply and bind cannot change the this point of the arrow function call, apply and bind can change the this point of ordinary functions
There is no arguments object. If there is an outer function, the argument of the outer function will be integrated. If there is no outer function, an error will be reported. The arrow function uses the rest parameter.
Without a generator, the yyield keyword cannot be used.
Does not have its own this, its this always points to its definition environment, and any method cannot change the pointing The this of an ordinary function always points to the object that calls it (whoever calls it points to whom)

Four, this keyword

  1. Appearing in global functions (ordinary functions, timer functions, and immediate execution functions) this always points to window, such as fun(); equivalent to window.fun()
  2. Appearing in strict mode will never point to window, use es5's strict mode 'use strict' in the function, this is undefined
  3. When called as a method, this points to the object that called the method.
  4. When called as a constructor, this points to the instance object created by the constructor.
  5. When called as an event-bound function, this points to the object that is bound to the event.
  6. When calling with call and apply, this points to the specified object in use.
  7. When this appears in an arrow function, this and the this of the parent scope point to the same.
  8. If used alone, this represents the global object.

Five, call and apply

  1. The functions of call and apply both change the scope of this, and both call functions in a specific scope. When an object does not have a certain method, but other objects do, we can use call or apply to realize the reuse of a certain method.
  2. The use of call and apply is basically the same, the only difference is their parameter rules: the call method accepts a parameter list, and the apply method accepts an array containing multiple parameters.
call(apply的功能和它一样)
“外卖员炒菜”:厨师.炒菜.call(外卖员)
“外卖员弹钢琴”:演奏家.弹钢琴.call(外卖员)、
“外卖员换轮胎”:修理工.换轮胎.call(外卖员)……

programmer.programming.call(delivery) // 打印结果:外卖员编程
programmer.programming.apply(delivery) // 打印结果:外卖员编程

programmer.programming.call(delivery, '炒菜', '弹钢琴', '换轮胎')
programmer.programming.apply(delivery, ['炒菜', '弹钢琴', '换轮胎'])

Article 5 from www.jianshu.com/p/5024cfcc7…

Six, the difference between undefined and null

null undefined
logical angle Represents a null object pointer, indicating that there is no object, that is, there should be no value there. Indicates an undefined domain or missing value
scenes to be used It can be used as a parameter of a function. When calling a function, if a parameter is not set to any value, null can be passed in, indicating that the parameter is empty. Under no circumstances is it necessary to explicitly set the value of a variable to undefined
type of data Object type Undefined type

Seven, variable promotion

Note that only declarations are hoisted, not initializations

variable hoisting (1) Variable promotion is very simple, that is, to lift variables to the top of the function. It should be noted that variable promotion only promotes variable declarations, and does not promote assignments.
(2) Function promotion is to bring the entire function to the front.
(3) Function hoisting takes precedence over variable hoisting.
reason (1) Improve performance
(2) Good fault tolerance
priority (1) The priority of function promotion is higher than that of variables
(2) Since both function declarations and variables are promoted, if the function has the same name as the variable, if only the function is printed before the variable assignment, all the variables are printed after the variable assignment value.
(3) Only function declarations are hoisted, not function expressions.
(4) What is declared first will be overwritten by what is declared later.

8. Prevent default behavior and event bubbling

1. Prevent default behavior

Default event: The browser's default event is the browser's own behavior. For example, when we click <a href="#">, the browser jumps to the specified page. Also, when we scroll the mouse, the page will scroll down, but when we press the space bar and the arrow keys, the page will also scroll down. For a better user experience, we need to prevent this behavior from happening.

Three ways to prevent the default behavior:

  • event.preventDefault();
  • The returnValue attribute of lower version browsers
  • return false;
function preventDefa(e){ 
  if(window.event){ 
    //IE中阻止函数器默认动作的方式  
    window.event.returnValue = false;  
  } 
  else{ 
    //阻止默认浏览器动作(W3C)  
    e.preventDefault(); 
  }  
}

This is a compatibility writing method, but if you only need to support high-version browsers, then as above, one sentence is enough.

obj.onclick = function (){ 
  return false; 
}

This method is more violent, it will prevent event bubbling and default event at the same time, write this code, the connection will not be opened, and the event will not be passed to the parent element of the upper layer; it can be understood as calling and at
the same return false;timeevent.stopPropagation()event.preventDefault()

2. Prevent event bubbling

We all know that bubbling is like the process of bubbles rising from the bottom of the water to the surface. The bubbling event is the process that the event passes through the upper level of events one by one from the bottom layer, which is the bubbling event. It is initially received by the most specific element, and then propagated up to the topmost node of the DOM.

Properties and methods of common event objects:

  • event.stopPropagation();
  • event.cancelBubble = true;

阻止事件冒泡的兼容性解决方案:

 if (e && e.stopPropagatio "){
    e.stopPropagation();
 }
 else {
     window.event.cancelBubble = true;
 }

3.&tips:vue 阻止向上和向下冒泡

<!--阻止向下冒泡-->
<div  @click.self="cancelFunc"></div> 
<!--阻止向上冒泡-->
<div  @click.stop="cancelFunc"></div>

九、操作符之间的优先级

1.JS中常用的运算符分为以下几类

算术运算符 + - * / % ++ –
赋值运算符 = += -= *= /= %=
逻辑运算符 && || !
关系运算符 < > <= >= == === != !==
三目运算符 n=n>m?a:b; (解释:n是否大于m,如果是,输出a,如果不是,输出b)

2. 优先级(高到低:)

算数操作符 → 比较操作符 → 布尔(逻辑)操作符 → “=”赋值符号 。 逻辑操作符中,逻辑与(&&)优先级高于逻辑或(||)

3. 实例:

var a = 4 >= 6 || true && 1 || false;
console.log(a);
答案:1

解析:
① 4 >= 6,结果是false(比较操作符返回布尔值)
② true && 1,结果是1(逻辑与的规则:第一个操作数是真值,则返回第二个操作数)
原式变为 false || 1 || false(按正常顺序执行)
③ false || 1,结果是1(逻辑或的规则:第一个操作数是假值,则返回第二个操作数)
④ 1 || false,结果是1(逻辑或的规则:第一个操作数是真值,则直接返回第一个操作数)

十、数据存储

1. cookie和session:

cookie session
数据存放在客户的浏览器上 数据放在服务器上
安全性较低,别人可以分析存放在本地的cookie并进行cookie欺骗,考虑到安全应当使用session 会在一定时间内保存在服务器上,当访问增多,会比较占用你服务器的性能,考虑到减轻服务器性能方面,应当使用cookie
cookie大小受限, 单个cookie保存的数据不能超过4KB,很多浏览器都限制一个站点最多保存20个cookie 建议将登录信息等重要信息存放为session,其他信息如果需要保留,可以放在cookie中

2. localStorag和sessionStorag:

localStorage sessionStorage
localStorage的生命周期是永久的,关闭页面或浏览器之后localStorage中的数据也不会消失。localStorage除非主动删除数据,否则数据永远不会消失。 sessionStorage的生命周期是在仅在当前会话下有效
sessionStorage引入了一个“浏览器窗口”的概念,
sessionStorage是在同源的窗口中始终存在的数据。只要这个浏览器窗口没有关闭,即使刷新页面或者进入同源另一个页面,数据依然存在。但是sessionStorage在关闭了浏览器窗口后就会被销毁。
同时独立的打开同一个窗口同一个页面,sessionStorage也是不一样的。
因此sessionStorage 和 localStorage 的主要区别在于他们存储数据的生命周期,
sessionStorage 存储的数据的生命周期是一个会话,
而 localStorage存储的数据的生命周期是永久,除非主动删除数据,否则永远不会过期
存储大小为5MB,都保存在客户端,不与服务器进行交互通信,

localStorage和sessionStorage有相同的Web API:

  1. 保存数据到本地
const info = {
    
    name: 'Lee',age: 20,id: '001' };
sessionStorage.setItem('key', JSON.stringify(info));
localStorage.setItem('key', JSON.stringify(info));
  1. 从本地存储获取数据
var data1 = JSON.parse(sessionStorage.getItem('key'));
var data2 = JSON.parse(localStorage.getItem('key'));

  1. 本地存储中删除某个保存的数据
sessionStorage.removeItem('key');
localStorage.removeItem('key');
  1. 删除所有保存的数据
sessionStorage.clear();
localStorage.clear();
  1. 监听本地存储的变化
window.addEventListener('storage', function (e) {
   console.log('key', e.key);
   console.log('oldValue', e.oldValue);
   console.log('newValue', e.newValue);
   console.log('url', e.url);
})

3. 总结:

数据存储位置、生命周期、存储大小、写入方式、数据共享、发送请求时是否携带、应用场景 标准回答 Cookie、SessionStorage、 LocalStorage都是浏览器的本地存储。

它们的共同点:都是存储在浏览器本地的。

它们的区别: cookie是由服务器端写入的,而SessionStorage、 LocalStorage都是由前端写入的,cookie的生命周期是由服务器端在写入的时候就设置好的,LocalStorage是写入就一直存在,除非手动清除,SessionStorage是页面关闭的时候就会自动清除。
cookie的存储空间比较小大概4KB,SessionStorage、 LocalStorage存储空间比较大,大概5M。
Cookie、SessionStorage、 LocalStorage数据共享都遵循同源原则,SessionStorage还限制必须是同一个页面。在前端给后端发送请求的时候会自动携带Cookie中的数据,但是SessionStorage、 LocalStorage不会 。
加分回答 由于它们的以上区别,所以它们的应用场景也不同,Cookie一般用于存储登录验证信息SessionID或者token,LocalStorage常用于存储不易变动的数据,减轻服务器的压力,SessionStorage可以用来检测用户是否是刷新进入页面,如音乐播放器恢复播放进度条的功能。

整理了一些JavaScript常见的面试题整理用于学习,如有问题欢迎指正,侵删~

 前端面试题库 (面试必备)            推荐:★★★★★

地址:前端面试题库

 Receive National Day avatar   [National Day avatar] - National Day patriotic programmer avatar! always one option fit for you!

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/132670752