javascript 重新声明箭头函数[重复]

szqfcxe2  于 2023-02-21  发布在  Java
关注(0)|答案(1)|浏览(129)
    • 此问题在此处已有答案**:

Why let and const keyword variables are not allowed to redeclaration in JavaScript, where var keyword variable is allowed?(1个答案)
delete or override const variables in javascript Harmony / ECMAScript 6(2个答案)
Why reassigning const producing error in console only if we do that in code editor? [duplicate](1个答案)
9小时前关门了。
尝试重新声明箭头函数--(检查代码)

var可以重新声明时,为什么它会给出错误。
我用var做了一个箭头函数,然后尝试用let重新声明它,因为var可以重新声明。但是为什么它会出错呢?

chhkpiq4

chhkpiq41#

如果你用var声明变量,你可以用var重新声明变量很多次,但是如果你用letconst重新声明,它会出错。用letconst,你只能声明一个变量。
您可能想要做的是重新分配变量,您可以使用varlet执行任意次数的重新分配,只是不要再次添加varlet

重新声明

// valid, but not advised
var cube = (num) => num * num * num;
var cube = (num) => num * num * num;
// invalid
var cube = (num) => num * num * num;
let cube = (num) => num * num * num;
// invalid
var cube = (num) => num * num * num;
const cube = (num) => num * num * num;

重新分配

// valid
var cube = (num) => num * num * num;
cube = (num) => num * num * num;
// valid
let cube = (num) => num * num * num;
cube = (num) => num * num * num;
// invalid - can't change a const
const cube = (num) => num * num * num;
cube = (num) => num * num * num;

相关问题