const numbers = [1,2,3,4,5]
let luckyNum = numbers.pop()数字的价值是什么?提示:数字存储在常量而不是变量中
2 回答

一只名叫tom的猫
TA贡献1906条经验 获得超3个赞
从MDN,您可以阅读:
常量是块作用域的,很像使用 let 语句定义的变量。常量的值不能通过 reassignment 改变,也不能重新声明。
在您的特定情况下,numbers变量保存对数组的引用,并且该引用将保持“常量”,而不是数组本身。您可以查看下一个示例:
const numbers = [1,2,3,4,5];
let luckyNum = numbers.pop();
console.log("luckyNum:", luckyNum, "numbers:", numbers);
// Now, next line will trhow an error, because we are
// trying to do a reassingment on a const variable:
numbers = [];
在您感兴趣的特定情况下,您可以使用Object.freeze()来禁止对array原始值的更改:
const numbers = [1, 2, 3, 4, 5];
Object.freeze(numbers);
// Now, next line will thrown an error.
let luckyNum = numbers.pop();
console.log("luckyNum:", luckyNum, "numbers:", numbers);
我希望这可以澄清您的疑虑。
添加回答
举报
0/150
提交
取消