Common JavaScript interview questions and answers

Here are some common JavaScript interview questions and answers:

1. What is a closure? Give an example to illustrate.

Closure means that the inner function can access the variables and parameters in the scope of the outer function, even if the outer function has returned. The following is an example of a closure:

function outer() {
  var x = 10;

  function inner() {
    console.log(x);
  }

  return inner;
}

var closure = outer();
closure(); // 输出 10

2. What is a prototype chain? How to use prototype chain to implement inheritance?

The prototype chain refers to __proto__the chain structure formed by the correlation between objects through attributes. Inheritance in JavaScript is implemented through the prototype chain. The following is an example of using the prototype chain to implement inheritance:

function Animal(name) {
  this.name = name;
}

Animal.prototype.sayName = function() {
  console.log(this.name);
};

function Dog(name) {
  Animal.call(this, name);
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.bark = function() {
  console.log('Woof!');
};

var dog = new Dog('Fido');
dog.sayName(); // 输出 'Fido'
dog.bark(); // 输出 'Woof!'

**

3. What is the event loop? How to understand asynchronous programming in JavaScript?

**

The event loop refers to the mechanism by which events and tasks are scheduled during the JavaScript runtime. JavaScript is single-threaded, so asynchronous programming is necessary to avoid blocking the main thread. Asynchronous programming can be implemented through callback functions, Promise and async/await.

  1. How to determine if a variable is an array?

You can use Array.isArray()the method to determine whether a variable is an array. For example:

var arr = [1, 2, 3];
console.log(Array.isArray(arr)); // 输出 true

var obj = { a: 1, b: 2 };
console.log(Array.isArray(obj)); // 输出 false

5. How to determine whether a variable is an object?

You can use typeofthe operator to determine whether a variable is an object. For example:

var obj = { a: 1, b: 2 };
console.log(typeof obj === 'object'); // 输出 true

var arr = [1, 2, 3];
console.log(typeof arr === 'object'); // 输出 true

var str = 'hello';
console.log(typeof str === 'object'); // 输出 false

6. How to implement classes in JavaScript?

There is no concept of classes in JavaScript, but constructors and prototypes can be used to achieve class-like functionality. The following is an example of an implementation class:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.sayName = function() {
  console.log(this.name);
};

Person.prototype.sayAge = function() {
  console.log(this.age);
};

var person = new Person('Alice', 30);
person.sayName(); // 输出 'Alice'
person.sayAge(); // 输出 30

7. How to achieve modularity in JavaScript?

Modularity in JavaScript can be achieved using CommonJS or ES6 modularity. Here is an example of modularization using CommonJS:

// math.js
function add(x, y) {
  return x + y;
}

module.exports = { add };

// main.js
var math = require('./math');

console.log(math.add(1, 2)); // 输出 3

8. How to implement array deduplication?

Array deduplication can be achieved using Seta data structure or looping through the array. The following is an Setexample of using array deduplication:

var arr = [1, 2, 3, 2, 1];
var uniqueArr = Array.from(new Set(arr));
console.log(uniqueArr); // 输出 [1, 2, 3]

9. How to reverse string?

You can use split()the and reverse()methods to reverse strings. Here is an example of string reversal:

var str = 'hello';
var reversedStr = str.split('').reverse().join('');
console.log(reversedStr); // 输出 'olleh'

10. How to determine whether a string is a palindrome string?

You can reverse the string first and then compare it with the original string. The following is an example of judging a palindrome string:

function isPalindrome(str) {
  var reversedStr = str.split('').reverse().join('');
  return str === reversedStr;
}

console.log(isPalindrome('racecar')); // 输出 true
console.log(isPalindrome('hello')); // 输出 false

11. How to implement function currying?

Function currying can be implemented using closures and recursion. Here is an example of implementing function currying:

function add(x) {
  return function(y) {
    return x + y;
  };
}

console.log(add(1)(2)); // 输出 3

12. How to implement function throttling?

Function throttling can be implemented using timers and timestamps. The following is an example of implementing function throttling:

function throttle(func, delay) {
  var lastTime = 0;

  return function() {
    var currentTime = Date.now();

    if (currentTime - lastTime > delay) {
      func.apply(this, arguments);
      lastTime = currentTime;
    }
  };
}

window.addEventListener('scroll', throttle(function() {
  console.log('scrolling');
}, 1000));

13. How to implement function anti-shake?

You can use timers to implement function anti-shake. The following is an example of implementing function anti-shake:

function debounce(func, delay) {
  var timer;

  return function() {
    clearTimeout(timer);

    timer = setTimeout(function() {
      func.apply(this, arguments);
    }, delay);
  };
}

window.addEventListener('scroll', debounce(function() {
  console.log('scrolling');
}, 1000));

14. How to get the query parameters in the URL?

You can use URLSearchParamsan object or a regular expression to get query parameters from the URL. The following is an example of using URLSearchParamsan object to obtain query parameters:

var searchParams = new URLSearchParams(window.location.search);

console.log(searchParams.get('q')); // 假设 URL 是 http://example.com/?q=hello,输出 'hello'

15. How to generate random numbers in JavaScript?

Math.random()Random numbers can be generated using the method. The following is an example of generating random numbers within a specified range:

function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(getRandomNumber(1, 10)); // 输出介于 1 和 10(含)之间的随机整数

16. How to convert string to number?

You can convert a string to a number using parseInt()the or method. parseFloat()Here is an example of converting a string to a number:

var str = '123';
var num = parseInt(str);

console.log(num); // 输出数字类型的值 123

17. How to convert number to string?

toString()Numbers can be converted to strings using the method. Here is an example of converting a number to a string:

var num = 123;
var str = num.toString();

console.log(str); // 输出字符串类型的值 '123'

18. How to determine whether a number is even?

You can use the modulo operator %to determine whether a number is even. If a number is divided by two and the remainder is zero, then the number is even. The following is an example of determining an even number:

function isEven(num) {
  return num % 2 === 0;
}

console.log(isEven(2)); // 输出 true
console.log(isEven(3)); // 输出 false

19. How to determine whether a number is prime?

You can use loop traversal and modulo operator %to determine whether a number is prime. A number is prime if it has a remainder when divided by all integers greater than one and less than the number itself. The following is an example of determining prime numbers:

function isPrime(num) {
  if (num <= 1) {
    return false;
  }

  for (var i = 2; i < num; i++) {
    if (num % i === 0) {
      return false;
    }
  }

  return true;
}

console.log(isPrime(2)); // 输出 true
console.log(isPrime(3)); // 输出 true
console.log(isPrime(4)); // 输出 false

20. How to get the current timestamp?

The current timestamp can be Date.now()obtained using the method. Here is an example of getting the current timestamp:

var timestamp = Date.now();

console.log(timestamp); // 输出当前时间戳(以毫秒为单位)

21. How to format datetime?

You can use Dateobjects and string concatenation to format date and time. Here is an example of formatting a datetime:

var date = new Date();
var year = date.getFullYear();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var hours = ('0' + date.getHours()).slice(-2);
var minutes = ('0' + date.getMinutes()).slice(-2);
var seconds = ('0' + date.getSeconds()).slice(-2);

var formattedDate = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;

console.log(formattedDate); // 输出格式化后的日期时间字符串,例如 '2023-07-03 15:30:00'

22. How to manipulate DOM elements in JavaScript?

You can use document.getElementById(), document.querySelector(), document.querySelectorAll()and other methods to obtain DOM elements, and then use the properties and methods on the element object to operate DOM elements. The following is an example of manipulating DOM elements:

// HTML: <div id="my-div">Hello</div>

var myDiv = document.getElementById('my-div');
myDiv.innerHTML = 'World';
myDiv.style.color = 'red';

23. How to add event listeners in JavaScript?

addEventListener()Event listeners can be added using the method on the element object . Here is an example of adding an event listener:

// HTML: <button id="my-button">Click me</button>

var myButton = document.getElementById('my-button');
myButton.addEventListener('click', function() {
  console.log('Button clicked');
});

24. How to create a new element in JavaScript and add it to the DOM?

You can create a new element using the methods on the element object , then set the element properties and content using the properties and methods on the element object, and finally add the element to the DOM createElement()using the methods on the element object . appendChild()Here is an example of creating a new element and adding it to the DOM:

// HTML: <div id="my-container"></div>

var myContainer = document.getElementById('my-container');
var myParagraph = document.createElement('p');
myParagraph.innerHTML = 'Hello';
myContainer.appendChild(myParagraph);

25. How to delete elements in JavaScript?

Elements can be deleted using the method on the element object removeChild()or the method on the parent element object . removeChild()Here is an example of removing an element:

// HTML: <div id="my-container"><p>Hello</p></div>

var myContainer = document.getElementById('my-container');
var myParagraph = document.querySelector('p');
myContainer.removeChild(myParagraph);

26. How to modify element attributes in JavaScript?

Element properties can be modified using properties and methods on the element object. For example, to modify classthe attribute of an element, you can use the attribute on the element object className; to modify the style of the element, you can use the attribute on the element object; to modify the content of the element, you can use the or attribute styleon the element object, etc. The following is an example of modifying element attributes:innerHTMLtextContent

// HTML: <div id="my-div" class="foo" style="color: red;">Hello</div>

var myDiv = document.getElementById('my-div');
myDiv.className += ' bar'; // 添加新 class
myDiv.style.backgroundColor = 'blue'; // 修改背景颜色
myDiv.textContent = 'World'; // 修改内容

27. How to get and modify form element values ​​in JavaScript?

You can obtain and modify form element values ​​using properties and methods on the form element object. For example, to get the value entered in the text box input box, you can use the property on the text box input box object ; to modify the selected state of the radio button or check box, you can use the properties valueon the radio button or check box object, etc. checked. The following is an example of getting and modifying the value of a form element:

// HTML: <input type="text" id="my-input">
//        <input type="checkbox" id="my-checkbox">

var myInput = document.getElementById('my-input');
console.log(myInput.value); // 获取文本框输入框中输入的值

var myCheckbox = document.getElementById('my-checkbox');
myCheckbox.checked = true; // 修改复选框选中状态

28. How to send AJAX request in JavaScript?

You can use XMLHttpRequestthe object or the Fetch API to send AJAX requests. The following is an example of using an XMLHttpRequestobject to send an AJAX request and process the response data:

function sendAjaxRequest(url, callback) {
  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {
    if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
      callback(xhr.responseText);
    }
  };

  xhr.open('GET', url);
  xhr.send();
}

sendAjaxRequest('https://jsonplaceholder.typicode.com/todos/1', function(responseText) {
  var data = JSON.parse(responseText);
  
  console.log(data.userId); // 输出响应数据中 userId 的值
});

29. How to handle exceptions in JavaScript?

You can use try...catchblocks to handle exceptions. tryWrite code that may throw exceptions in a block, handle the exception situation and take appropriate action in the catchblock. The following is an example of handling exceptions:

try {
  var result = someFunctionThatMayThrowAnError();
} catch (error) {
  console.error(error.message);
}

30. How to do unit testing in JavaScript?

Unit testing can be done using testing frameworks (such as Mocha, Jasmine, QUnit, etc.) and assertion libraries (such as Chai, Expect.js, etc.). Write test cases, execute tests, and debug and fix code defects based on test results. For example, here's how to write and execute test cases in Mocha and Chai:

// 安装 Mocha 和 Chai:
// npm install --save-dev mocha chai

// 编写测试用例:
describe('someFunction', function() {
  it('should return the correct result', function() {
    var result = someFunction(1, 2);

    expect(result).to.equal(3);
  });
});

// 执行测试:
// mocha test.js

Guess you like

Origin blog.csdn.net/weixin_45441470/article/details/131519978