interview
javascript-frontend-basics
为什么 JavaScript 函数的 arguments 参数是类数组而不是数组如何遍历类数组

前端 JavaScript 基础面试题, 为什么 JavaScript 函数的 arguments 参数是类数组而不是数组?如何遍历类数组?

前端 JavaScript 基础面试题, 为什么 JavaScript 函数的 arguments 参数是类数组而不是数组?如何遍历类数组?

QA

Step 1

Q:: 为什么 JavaScript 函数的 arguments 参数是类数组而不是数组?

A:: JavaScript 函数的 arguments 参数是类数组而不是数组,因为 arguments 对象是一个类数组对象,其索引属性从 0 开始,表示传给函数的参数,具有 length 属性,但不具备数组的方法。这样设计是因为 arguments 对象的主要目的是为了访问函数的参数,而不需要提供数组的完整功能。如果需要将 arguments 转换为真正的数组,可以使用 Array.from() 或 Array.prototype.slice.call(arguments) 方法。

Step 2

Q:: 如何遍历类数组?

A:: 可以使用 for 循环遍历类数组对象。例如:

 
function example() {
  for (let i = 0; i < arguments.length; i++) {
    console.log(arguments[i]);
  }
}
example(1, 2, 3);
 

此外,也可以使用 Array.from() 方法将类数组对象转换为数组后再进行遍历:

 
function example() {
  Array.from(arguments).forEach(arg => console.log(arg));
}
example(1, 2, 3);
 

用途

面试这个内容是因为在实际生产环境中,JavaScript 函数的 arguments 对象在处理不定数量的参数时非常有用。了解如何使用和遍历 arguments 对象能够提高代码的灵活性和通用性。在编写一些通用函数、库函数或处理动态参数时会用到这些知识。\n

相关问题

🦆
什么是 JavaScript 中的类数组对象?

类数组对象是拥有一个 length 属性和索引属性的对象,类似于数组,但不具备数组的所有方法。常见的类数组对象包括 arguments 对象、DOM 方法返回的 NodeList 等。

🦆
如何将类数组对象转换为数组?

可以使用 Array.from() 方法或 Array.prototype.slice.call() 方法将类数组对象转换为数组。例如:

 
const arrayLike = {0: 'a', 1: 'b', length: 2};
const arr = Array.from(arrayLike); // ['a', 'b']
const arr2 = Array.prototype.slice.call(arrayLike); // ['a', 'b']
 
🦆
在什么情况下应该使用 rest 参数代替 arguments 对象?

在 ES6 中,rest 参数(...) 提供了更好的语法和功能来处理函数的不定数量参数。相比 arguments 对象,rest 参数是真正的数组,可以直接使用数组的方法,且语义更清晰。通常在新代码中建议使用 rest 参数代替 arguments 对象。

 
function example(...args) {
  args.forEach(arg => console.log(arg));
}
example(1, 2, 3);
 
🦆
什么是 JavaScript 中的闭包?

闭包是指那些能够访问其词法作用域(lexical scope)内变量的函数,即使该函数是在其词法作用域之外执行的。闭包可以用于创建私有变量,模拟块级作用域等。

 
function outer() {
  let privateVar = 'I am private';
  return function() {
    console.log(privateVar);
  }
}
const inner = outer();
inner(); // 'I am private'
 
🦆
JavaScript 中的 this 关键字是如何工作的?

this 关键字的值取决于函数的调用方式。在全局环境中,this 指向全局对象(在浏览器中是 window);在对象的方法中,this 指向调用该方法的对象;在构造函数中,this 指向新创建的对象;在箭头函数中,this 由函数定义时的作用域决定。

 
function test() {
  console.log(this);
}
test(); // window (在浏览器中)
const obj = {method: test};
obj.method(); // obj