温馨提示×

const关键字在函数参数中的应用

小樊
81
2024-09-20 10:31:17
栏目: 编程语言

在JavaScript中,const关键字用于声明一个常量变量,即其值在声明后不能被修改。当我们将const应用于函数参数时,这意味着该参数在函数内部是一个常量,不能重新赋值。这有助于提高代码的可读性和可维护性,因为我们可以清楚地知道哪些变量不应该被修改。

以下是一个使用const关键字的函数参数的示例:

function sum(a, b) {
  if (typeof a !== 'number' || typeof b !== 'number') {
    throw new Error('Both arguments must be numbers');
  }

  const result = a + b;
  console.log('The sum of', a, 'and', b, 'is', result);
  return result;
}

sum(1, 2); // 输出 "The sum of 1 and 2 is 3"
sum(3, 4); // 输出 "The sum of 3 and 4 is 7"

// sum(1, '2'); // 将抛出错误,因为参数类型不正确

在这个例子中,我们将ab参数声明为const,这意味着它们在函数内部不能被重新赋值。如果尝试这样做,将会抛出一个错误。这有助于确保我们在使用这些参数时始终遵循正确的数据类型。

0