Front-end interview questions JS articles (1) - review of knowledge points

1. What is the output of the following code

var a = 1;
console.log(a++ * (++a + a++));

Analysis:
The difference between a++ and ++a:

  • a++ returns the original value, ++a returns the value after adding 1.
  • a++ cannot be an lvalue, but ++a can.
  • a++The former is to assign a value first, and then increment; ++aThe latter is to increment first, and then assign a value.

insert image description hereinsert image description here
a=1; a++ = 1; a=2; ++a = 3; a=3; a++ = 3;
a++ * (++a + a++)= 1 * ( 3+3 ) = 6
Answer: 6

2. What are the latest JS data types?

  • At the time of ES5, the data types we recognized were indeed 6 types: Number, String, Boolean, undefined, object,Null
  • One was added in ES6 Symbol . Objects of this type are never equal, that is, the same value is passed in at the beginning of creation, which can solve the problem of property name conflicts and serve as a mark.
  • One more appeared in Google version 67 bigInt. Refers to safe storage and manipulation of large integers.

At present, there are 8 types of JS data types , which can be divided into basic data types and reference data types according to types:
basic data types : Number, String, Boolean, undefined, Null, Symbol, bigInt;
reference data types : Object(Object is a large category, including Array array, function function, Date date, etc.)

The difference between basic data types and reference data types

1. Different memory allocation when declaring variables

  • Basic data type: Since the space occupied is fixed and small, it will be stored in it, that is, the location of variable access
  • Reference data type: stored in it, the variable accessed is actually a pointer, which points to the memory address of the stored object

2. Because the memory allocation is different, the result is different when copying variables

  • After the basic data type is copied, the two variables are independent and do not affect each other, because the value is copied

  • The reference data type is to copy a pointer . The value pointed by the two variables is the content pointed by the pointer. Once one is modified, the other will also be affected.

    This actually involves deep copy and shallow copy of JS

3. Parameter passing is different

  • Basic data type: pass the value in the variable to the parameter, and then the parameter and the variable will not affect each other
  • Reference data type (take function as an example here): Although the parameters of the function are passed by value, the value passed by the reference value is a memory address , and the actual parameter and the formal parameter point to the same object, so the internal parameter of the function Modifications of the will be reflected in the external

3. Deep copy and shallow copy

1. Basic data types

// 基本数据类型
// 赋值(不是深拷贝也不是浅拷贝)(非要说就是深拷贝)(互不影响)
let a = 5;
let b = a;
b = 3;
console.log(a,b);// 5,3

2. Reference data type

  • Assignment of arrays and objects
// 数组与对象的赋值
// 浅拷贝 (藕断丝连)
let arr = [1,2,3];
let newarr = arr;
newarr.push(4);
console.log(arr);    // [1,2,3,4]
console.log(newarr); // [1,2,3,4]
  • destructuring assignment
// 解构赋值
// 针对一维数组和对象可以看作是深拷贝,多维就是浅拷贝
let arr = [1,2,3];
let newarr = [...arr];
newarr.push(4);
console.log(arr);    // [1,2,3]
console.log(newarr); // [1,2,3,4]

let arr2 = [[1,2,3],[4,5,6]];
let newarr2= [...arr2];
newarr2.push(888)
console.log(arr2); 	   // [[1,2,3],[4,5,6],888]
console.log(newarr2);  // [[1,2,3],[4,5,6],888]

Summarize:

  • Deep copy: refers to the fact that the source object and the copy object are independent of each other , and any change of one object will not affect the other object, and the two variables are independent of each other and do not affect each other; ) (basic data type assignment )
  • Shallow copy: refers to the disconnection between the source object and the copy object ; (assignment of reference data type)

Exercise: What is the output of the following code?

var a = {
    
    
	n: 0,
}
var b = a;
a.n = a = {
    
    n:1};
console.log(b.n);

Answer: { n: 1 }
insert image description here

4. Usage of deep copy

4.1 Using JSON's built-in methods
// 深拷贝的用法
let list = [
	{
    
    id:1,name:'aaa',sex:'01'},
	{
    
    id:2,name:'bbb',sex:'02'},
	{
    
    id:3,name:'ccc',sex:'01'},
]
// let newlist = list;  // 对象赋值是浅拷贝
let newlist = JSON.parse(JSON.stringify(list)); // 利用JSON.parse(JSON.stringify())转化为深拷贝
newlist.push({
    
    id:44});
console.log(list === newlist); // false

This method is to use JSON.stringify to serialize the object into a string, and then use JSON.parse to parse the json string into an object. When parsing, it will build a new memory address to store the new object.

shortcoming:

  • undefined will be ignored;
  • symbol will be ignored;
  • If the property of the object is Function, because the JSON format string does not support Function, it will be automatically deleted during serialization;
  • Built-in types such as Map, Set, RegExp, Date, ArrayBuffer and others are lost during serialization;
  • Copying of circularly referenced objects is not supported.
4.2 Standard deep copy (recursive deep copy)
// 标准的数据类型 =>引用数据类型(数组和对象)
function deepCopy(obj) {
    
    
	  // 创建一个新对象
	  let result = {
    
    }
	  let keys = Object.keys(obj),
	      key = null,
	      temp = null;
	
	  for (let i = 0; i < keys.length; i++) {
    
    
	      key = keys[i];    
	      temp = obj[key];
	      // 如果字段的值也是一个对象则递归操作
	      if (temp && typeof temp === 'object') {
    
    
	          result[key] = deepCopy(temp);
	      } else {
    
    
	      // 否则直接赋值给新对象
	          result[key] = temp;
	      }
	  }
	  return result;
}
let obj={
    
    
	str:'name',
	num:123,
	arr:[1,2,3,4],
	obj:{
    
    id:1,student:'小米'}
}
let newobj=deepClone(obj);
newobj.str="新值";
console.log(obj === newobj); // false
4.3 The ultimate perfect solution: lodash

lodash 's _.cloneDeep() supports circular objects and a large number of built-in types, and handles many details well. It is recommended to use.

var _ = require('lodash');
var obj1 = {
    
    
    a: 1,
    b: {
    
     f: {
    
     g: 1 } },
    c: [1, 2, 3]
};
var obj2 = _.cloneDeep(obj1);
console.log(obj1.b.f === obj2.b.f);// false

So, how does lodash solve the problem of circular references? Check out the source code:
insert image description here

You will find that lodash uses a stack to record all copied reference values. If the same reference value is encountered again, it will not copy it again, but use the copy that has been copied before.
In summary, in a production environment, we recommend using lodash's cloneDeep().

5. Where should performance optimization be done?

  • page load performance
    • Reduce http requests (sprites, file merging)
    • Reduce file size (resource compression, image compression, code compression)
    • CDN (referring to third-party libraries, large files, and large images)
    • SSR server-side rendering, pre-rendering
    • lazy loading
    • Subcontract
  • animation and performance
    • Reduce dom operations, avoid reflow, and document fragmentation

To be continued, it is being updated continuously, like, collect and pay attention, so that it will be convenient for the next review~

Guess you like

Origin blog.csdn.net/qq_38970408/article/details/127773746