JavaScript interview questions series (6) 10 questions each

1. JS judges whether a variable is an array, please list multiple methods

In JavaScript, there are several ways to determine whether a variable is an array. The following are several commonly used methods:

  1. Array.isArray() method : Array.isArray()It is a built-in method in JavaScript, which is used to determine whether a variable is an array.
const arr = [1, 2, 3];
console.log(Array.isArray(arr)); // 输出: true

const notArr = 'Hello';
console.log(Array.isArray(notArr)); // 输出: false
  1. instanceof operator : Use instanceofthe operator to determine whether an object is an instance of a constructor, thereby determining whether it is an array.
const arr = [1, 2, 3];
console.log(arr instanceof Array); // 输出: true

const notArr = 'Hello';
console.log(notArr instanceof Array); // 输出: false
  1. Array.prototype.isPrototypeOf() method : You can use Array.prototype.isPrototypeOf()the method to check the prototype chain to determine whether an object is an array.
const arr = [1, 2, 3];
console.log(Array.prototype.isPrototypeOf(arr)); // 输出: true

const notArr = 'Hello';
console.log(Array.prototype.isPrototypeOf(notArr)); // 输出: false
  1. Object.prototype.toString.call() methodObject.prototype.toString.call() : Get the value of the internal property of the object through the method [[Class]], and then make a judgment.
const arr = [1, 2, 3];
console.log(Object.prototype.toString.call(arr) === '[object Array]'); // 输出: true

const notArr = 'Hello';
console.log(Object.prototype.toString.call(notArr) === '[object Array]'); // 输出: false

These methods can be used to determine whether a variable is an array. Of these methods, Array.isArray()is the most commonly used because it is simple and straightforward, and it performs more reliably when dealing with multiple global execution contexts or across windows. In addition, according to specific usage scenarios, other methods can also be selected for judgment.

2. The method of JS array deduplication, please list multiple methods

In JavaScript, there are several ways to deduplicate an array. Here are some commonly used deduplication methods:

  1. Use Set : Set in ES6 is a data structure that can help us quickly remove duplicate elements in an array.
const arr = [1, 2, 2, 3, 3, 4, 5];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // 输出: [1, 2, 3, 4, 5]
  1. Use indexOf() and filter() : By traversing the array, use the indexOf() method to determine whether the element is already in the result array, and then use the filter() method to filter duplicate elements.
const arr = [1, 2, 2, 3, 3, 4, 5];
const uniqueArr = arr.filter((item, index) => arr.indexOf(item) === index);
console.log(uniqueArr); // 输出: [1, 2, 3, 4, 5]
  1. Use includes() and filter() : Similar to above, use includes() method to determine whether the element is already in the result array.
const arr = [1, 2, 2, 3, 3, 4, 5];
const uniqueArr = arr.filter((item, index) => arr.includes(item, index + 1) === false);
console.log(uniqueArr); // 输出: [1, 2, 3, 4, 5]
  1. Use reduce() : Use the reduce() method with an empty array to remove duplicate elements.
const arr = [1, 2, 2, 3, 3, 4, 5];
const uniqueArr = arr.reduce((acc, cur) => acc.includes(cur) ? acc : [...acc, cur], []);
console.log(uniqueArr); // 输出: [1, 2, 3, 4, 5]
  1. Use Map : Use the Map data structure to deduplicate.
const arr = [1, 2, 2, 3, 3, 4, 5];
const uniqueArr = Array.from(new Map(arr.map(item => [item, item])).values());
console.log(uniqueArr); // 输出: [1, 2, 3, 4, 5]
  1. Use filter() and indexOf() : Similar to the second method, but use the return value of the indexOf() method to determine whether the element is the first to appear.
const arr = [1, 2, 2, 3, 3, 4, 5];
const uniqueArr = arr.filter((item, index) => arr.indexOf(item) === index);
console.log(uniqueArr); // 输出: [1, 2, 3, 4, 5]

All of the above methods can be used to deduplicate arrays, and which method to choose depends on specific requirements and scenarios. In general, using a Set is the most concise and efficient approach, but other approaches may be considered if compatibility with older environments is required.

3. JS finds the maximum value of a multidimensional array, please list a variety of methods

In JavaScript, there are several ways to find the maximum value in a multidimensional array. Here are some commonly used methods:

  1. Using Math.max() and apply() : Expand the multidimensional array into a one-dimensional array, then use Math.max() and apply() to find the maximum value.
const multiDimArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const flattenedArray = multiDimArray.flat();
const maxVal = Math.max.apply(null, flattenedArray);
console.log(maxVal); // 输出: 9
  1. Use reduce() : Use the reduce() method to traverse the multidimensional array to find the maximum value.
const multiDimArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const maxVal = multiDimArray.reduce((max, arr) => Math.max(max, ...arr), -Infinity);
console.log(maxVal); // 输出: 9
  1. Using recursion : Write a recursive function to iterate through a multidimensional array, finding the maximum value.
function findMaxValue(arr) {
    
    
  let maxVal = -Infinity;
  for (let item of arr) {
    
    
    if (Array.isArray(item)) {
    
    
      maxVal = Math.max(maxVal, findMaxValue(item));
    } else {
    
    
      maxVal = Math.max(maxVal, item);
    }
  }
  return maxVal;
}

const multiDimArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const maxVal = findMaxValue(multiDimArray);
console.log(maxVal); // 输出: 9
  1. Using recursion and spread operator : Similar to the third method, but uses the spread operator to spread the array.
function findMaxValue(arr) {
    
    
  let maxVal = -Infinity;
  for (let item of arr) {
    
    
    if (Array.isArray(item)) {
    
    
      maxVal = Math.max(maxVal, ...findMaxValue(item));
    } else {
    
    
      maxVal = Math.max(maxVal, item);
    }
  }
  return [maxVal];
}

const multiDimArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const maxVal = findMaxValue(multiDimArray)[0];
console.log(maxVal); // 输出: 9

Either of these methods can be used to find the maximum value in a multidimensional array, and which method to choose is a matter of personal preference and code readability. It should be noted that when dealing with large multidimensional arrays, recursive methods may cause stack overflow, so it is best to use iterative methods or unroll the array to deal with it.

4. JS finds out the characters and times that appear most frequently in a string, please list a variety of methods

In JavaScript, there are several ways to find out which character occurs most often in a string and how many times it occurs. Here are some commonly used methods:

  1. Use object counting : iterate through the string, use an object to count the number of occurrences of each character, and find the character with the most occurrences.
function findMostFrequentChar(str) {
    
    
  const charCount = {
    
    };
  for (let char of str) {
    
    
    charCount[char] = (charCount[char] || 0) + 1;
  }

  let maxChar = '';
  let maxCount = 0;
  for (let char in charCount) {
    
    
    if (charCount[char] > maxCount) {
    
    
      maxChar = char;
      maxCount = charCount[char];
    }
  }

  return {
    
     char: maxChar, count: maxCount };
}

const inputString = 'abracadabra';
const result = findMostFrequentChar(inputString);
console.log(result); // 输出: { char: 'a', count: 5 }
  1. Using Map Counting : Similar to Object Counting, but uses a Map data structure to count occurrences of characters.
function findMostFrequentChar(str) {
    
    
  const charCount = new Map();
  for (let char of str) {
    
    
    charCount.set(char, (charCount.get(char) || 0) + 1);
  }

  let maxChar = '';
  let maxCount = 0;
  for (let [char, count] of charCount) {
    
    
    if (count > maxCount) {
    
    
      maxChar = char;
      maxCount = count;
    }
  }

  return {
    
     char: maxChar, count: maxCount };
}

const inputString = 'abracadabra';
const result = findMostFrequentChar(inputString);
console.log(result); // 输出: { char: 'a', count: 5 }
  1. Using Array Sort : Convert the string to an array, then use Array Sort to find the character with the most occurrences.
function findMostFrequentChar(str) {
    
    
  const charArr = str.split('').sort();
  let maxChar = charArr[0];
  let maxCount = 1;
  let currentChar = charArr[0];
  let currentCount = 1;

  for (let i = 1; i < charArr.length; i++) {
    
    
    if (charArr[i] === currentChar) {
    
    
      currentCount++;
    } else {
    
    
      currentChar = charArr[i];
      currentCount = 1;
    }

    if (currentCount > maxCount) {
    
    
      maxChar = currentChar;
      maxCount = currentCount;
    }
  }

  return {
    
     char: maxChar, count: maxCount };
}

const inputString = 'abracadabra';
const result = findMostFrequentChar(inputString);
console.log(result); // 输出: { char: 'a', count: 5 }

Either of these methods can be used to find the most frequently occurring character in a string and how many times, the choice of which method to use depends on personal preference and code readability. The above approach has low time complexity and is able to handle larger strings efficiently.

5.JS adds a new method to the string to realize the function, please list a variety of methods

In JavaScript, there are several ways to add content to a string. However, it is important to note that since strings are immutable data types, this means that once a string has been created, its contents cannot be directly modified. So, we can't actually add content directly to the original string, but need to create a new string. Here are some commonly used methods:

  1. Use string concatenation : add content via the string concatenation operator ( +) or string templates (template literals in ES6).
let str = 'Hello';
str = str + ' World'; // 使用 + 运算符
console.log(str); // 输出: 'Hello World'

let name = 'John';
const greeting = `Welcome, ${
      
      name}!`; // 使用字符串模板
console.log(greeting); // 输出: 'Welcome, John!'
  1. Use the concat() method : Use concat()the method to concatenate one or more strings to the original string and return a new string.
let str = 'Hello';
str = str.concat(' World', '!');
console.log(str); // 输出: 'Hello World!'
  1. Using string insertion methods : eg slice(), substr()or substring()can be used to insert content at a specific position.
let str = 'Hello';
const inserted = str.slice(0, 2) + 'XX' + str.slice(2);
console.log(inserted); // 输出: 'HeXXllo'
  1. Use the Array.join() method : convert the string to an array, then use Array.join()the method to insert content between the array elements.
let str = 'Hello';
const arr = str.split('');
arr.splice(2, 0, 'XX');
str = arr.join('');
console.log(str); // 输出: 'HeXXllo'

It should be noted that although we cannot directly modify the content on the original string, these methods can help us create a new string and achieve the effect of adding content. When choosing a method, choose the most appropriate method according to your specific needs and scenarios.

6. What exactly does the new operator in JS do?

In JavaScript, newthe operator is used to create an object instance and call the constructor to initialize the object. When using newthe operator to create an object, the specific steps are as follows:

  1. Create an empty object: newThe operator first creates an empty JavaScript object.

  2. Point the prototype of the object to the prototype of the constructor: the prototype of the newly created empty object will be set as a prototypeproperty of the constructor, so that the new object can access the methods and properties on the prototype of the constructor.

  3. Executing the constructor: The constructor will be called and the newly created object will be bound to this. Inside the constructor, we can use to thisrefer to the new object, and perform attribute assignment and other initialization operations on it.

  4. Returns an object instance: If no other object is explicitly returned in the constructor, newthe operator returns a newly created object instance. If there is a return value in the constructor, and the return value is an object, then newthe operator will return that object, not the newly created object instance.

Here's a simple constructor and newan example of creating an object using the operator:

// 构造函数
function Person(name, age) {
    
    
  this.name = name;
  this.age = age;
  this.sayHello = function() {
    
    
    console.log(`Hello, my name is ${
      
      this.name}, and I am ${
      
      this.age} years old.`);
  };
}

// 使用 new 操作符创建对象
const john = new Person('John', 30);
john.sayHello(); // 输出: 'Hello, my name is John, and I am 30 years old.'

It should be noted that newthe operator should be used with caution, especially if the operator is not used correctly thisor forgotten to be used inside the constructor new, it may cause errors or unexpected results. At the same time, newoperators will also bring some performance overhead, so in modern JavaScript, more classes (classes in ES6) are used to create objects, which provides a clearer, more readable and easier to maintain syntax.

7. What are the ways of JS inheritance

In JavaScript, there are several ways to implement inheritance. The following are some common inheritance methods:

  1. Prototype chain inheritance : use the prototype chain to achieve inheritance. Use the instance of the parent class as the prototype of the subclass, so that the subclass can access the properties and methods of the parent class.
function Parent() {
    
    
  this.name = 'Parent';
}

Parent.prototype.sayHello = function() {
    
    
  console.log('Hello, I am ' + this.name);
};

function Child() {
    
    }

Child.prototype = new Parent();

const child = new Child();
child.sayHello(); // 输出: 'Hello, I am Parent'

The disadvantage of prototype chain inheritance is that all subclass instances share the properties of the parent class instance, and the subclass cannot pass parameters to the parent class.

  1. Constructor inheritance : Inheritance is achieved by calling the parent class constructor in the subclass constructor.
function Parent(name) {
    
    
  this.name = name || 'Parent';
}

function Child(name) {
    
    
  Parent.call(this, name);
}

const child = new Child('John');
console.log(child.name); // 输出: 'John'

The advantage of constructor inheritance is that subclass instances have independent properties and do not share properties of parent class instances. But the downside is that subclasses cannot access methods on the prototype of the parent class.

  1. Combined inheritance : Combining prototype chain inheritance and constructor inheritance, the subclass can have both the properties and methods of the parent class.
function Parent(name) {
    
    
  this.name = name || 'Parent';
}

Parent.prototype.sayHello = function() {
    
    
  console.log('Hello, I am ' + this.name);
};

function Child(name) {
    
    
  Parent.call(this, name);
}

Child.prototype = new Parent();

const child = new Child('John');
child.sayHello(); // 输出: 'Hello, I am John'

The advantage of combined inheritance is that subclass instances not only have independent attributes, but also can access methods on the parent class prototype. But the disadvantage is that the constructor of the parent class will be called twice, once when the subclass instance is created, and once when the parent class instance is used as the subclass prototype.

  1. Class inheritance in ES6 : ES6 introduced classthe keyword to make inheritance more intuitive and easy to use.
class Parent {
    
    
  constructor(name) {
    
    
    this.name = name || 'Parent';
  }

  sayHello() {
    
    
    console.log('Hello, I am ' + this.name);
  }
}

class Child extends Parent {
    
    
  constructor(name) {
    
    
    super(name);
  }
}

const child = new Child('John');
child.sayHello(); // 输出: 'Hello, I am John'

ES6 class inheritance is more concise and readable, and it does not have some problems with prototype chain inheritance and constructor inheritance.

These are the common ways of inheritance in JavaScript, and each way has its applicable scenarios and advantages and disadvantages. When choosing an inheritance method, you should decide which method to use based on your actual needs and code structure.

8. Understanding of JS deep copy and shallow copy

Deep Copy and Shallow Copy are two different ways to copy objects in JavaScript.

Shallow copy :
Shallow copy refers to copying only the first-level properties of the object. If the properties of the object are reference types (such as arrays, objects, etc.), the references are copied instead of the real values. This means that the original object and the copied object will share the same reference type properties, and modifying the properties of one object will affect the other object. In JavaScript, you can use Object.assign()the method or the spread operator ( ...) to make a shallow copy.

// 使用 Object.assign() 进行浅拷贝
const obj1 = {
    
     name: 'John', age: 30 };
const shallowCopy = Object.assign({
    
    }, obj1);

// 使用扩展运算符进行浅拷贝
const obj2 = {
    
     name: 'Jane', age: 25 };
const shallowCopy2 = {
    
     ...obj2 };

Deep copy :
Deep copy refers to copying an object and all its nested properties into a new object, so that the original object and the copied object are completely independent and do not affect each other. A deep copy recursively copies all properties of an object, including properties of reference types. In JavaScript, commonly used deep copy methods include using recursive implementation, JSON.parse()and JSON.stringify()combining methods.

// 使用递归实现深拷贝
function deepCopy(obj) {
    
    
  if (obj === null || typeof obj !== 'object') {
    
    
    return obj;
  }

  let copy;
  if (Array.isArray(obj)) {
    
    
    copy = [];
    obj.forEach((item, index) => {
    
    
      copy[index] = deepCopy(item);
    });
  } else {
    
    
    copy = {
    
    };
    for (let key in obj) {
    
    
      if (obj.hasOwnProperty(key)) {
    
    
        copy[key] = deepCopy(obj[key]);
      }
    }
  }

  return copy;
}

const obj = {
    
     name: 'Alice', age: 28, hobbies: ['reading', 'coding'] };
const deepCopiedObj = deepCopy(obj);

A deep copy creates a completely independent new object, which means that modifying the copied object will not affect the original object.

It should be noted that deep copying may have performance overhead, especially for objects that are deeply nested or contain a large amount of data. Therefore, when choosing a copy method, you need to consider whether to use shallow copy or deep copy according to the actual situation.

9. The difference between localStorage, sessionStorage, and cookie

localStorage, sessionStorageand cookieare three different mechanisms used to store data in the browser. They both allow data to be stored on the client side for data sharing between pages under the same domain name. However, they have some differences in terms of storage, scope, and data validity.

  1. localStorage

    • Storage method: localStorageuse key-value pairs (key-value) to store data.
    • Scope: localStorageThe stored data is shared among all pages under the same domain name, and the data still exists even after the page is closed.
    • Data validity period: localStorageThe data has no expiration time, unless it is actively deleted or the browser cache is cleared, the data will always exist.
    • Storage size: Normally, localStoragethe storage limit for each domain name is 5MB.
  2. sessionStorage

    • Storage method: sessionStoragedata is also stored in the form of key-value pairs.
    • Scope: sessionStorageThe stored data is shared in the same browser window or tab, and the data between different windows or tabs is isolated. When the page is closed, sessionStoragethe data in it will also be cleared.
    • Data validity period: sessionStorageThe data in the page is automatically deleted when the page session ends, or it is also cleared when the page is closed.
    • Storage size: Normally, sessionStoragethe storage limit for each domain name is 5MB.
  3. cookie

    • Storage method: cookiedata is also stored in the form of key-value pairs.
    • Scope: cookieThe stored data is shared among all pages under the same domain name, including different windows or tabs.
    • Data validity period: cookieYou can set an expiration time. If no expiration time is set, the data cookiewill be cleared after the user closes the browser, otherwise it will exist until the expiration time is reached.
    • Storage size: Normally, cookiethe upper limit of storage for each domain name is 4KB.

Summarize:

  • localStorageand sessionStorageare HTML5's new Web Storage API, which provides a more efficient local storage method, but cookieis an old storage mechanism, mainly used for communication between the client and the server.
  • localStoragesessionStorageSimilar to the scope of , but the localStoragedata of will still exist after the page is closed, and sessionStoragethe data of will be cleared when the page is closed.
  • localStorageand have a much larger sessionStoragemaximum size limit for storing data than cookie.
  • localStorageThe use of and sessionStorageis simpler and more convenient, and does not need to manually handle the expiration time, but cookieneeds to set the expiration time or process it in the backend.

10. The difference between var, let, and const

In JavaScript, var, letand constare three keywords used to declare variables. They have some differences in terms of scope, variable hoisting, and modifiability.

  1. scope :

    • var: Variables declared using varhave function scope, that is, variables declared inside a function are only valid inside the function. If vara declared variable is used outside the function, it becomes a global variable.
    • letAnd const: Variables declared using letand consthave block-level scope, that is, variables declared within the nearest pair of curly braces ( {}) are only valid inside the block.
  2. Variable hoisting :

    • var: varA variable declared with will undergo variable promotion, that is, the variable can be accessed before the variable declaration, but the value is undefined. varThis is because JavaScript hoists declared variables to the top of a function or global scope before executing code .
    • letand const: variables declared with letand constalso undergo variable hoisting, but unlike varthem, they are not accessible until the variable declaration, known as a "temporary dead zone".
console.log(a); // 输出: undefined
var a = 10;

console.log(b); // 报错: Uncaught ReferenceError: Cannot access 'b' before initialization
let b = 20;

console.log(c); // 报错: Uncaught ReferenceError: Cannot access 'c' before initialization
const c = 30;
  1. Modifiability :
    • varAnd let: The value of variables declared with varand can be modified.let
    • const: constVariables declared using are constants, their values ​​cannot be reassigned, and cannot be changed once assigned. But for objects and arrays, although variables cannot be reassigned, attributes or elements of objects and arrays can still be modified.
var x = 10;
x = 20; // 可以修改

let y = 30;
y = 40; // 可以修改

const z = 50;
z = 60; // 报错: Uncaught TypeError: Assignment to constant variable.

const obj = {
    
     name: 'John' };
obj.age = 30; // 可以修改对象的属性

const arr = [1, 2, 3];
arr.push(4); // 可以修改数组的元素

Summarize:

  • varThere is function scope, variables are hoisted, and values ​​can be modified.
  • letThere is block scope, variables are hoisted (but with a temporary dead zone), and values ​​can be modified.
  • constThere is block-level scope, variable promotion (with a temporary dead zone), and cannot be reassigned, but for objects and arrays, its properties or elements can be modified.

Guess you like

Origin blog.csdn.net/weixin_52003205/article/details/131777619