为什么我可以将 const 与 Array.slice() 一起使用并仍然分配新值?

HJW*_*HJW 1 javascript arrays reactjs

只是注意到我启动了一个 const 并且Array.slice()仍然能够像这样为其分配一个值:

const clickTarget = e.target.innerHTML;
const newState = settings.slice();
const settingIndex = settings.indexOf(setting);

newState[settingIndex].setTo = clickTarget;

setSettings(newState);
Run Code Online (Sandbox Code Playgroud)

上下文:点击处理函数。

是否应该出现一个错误,表明您无法使用常量分配新值?我有预感,这是由于切片仅引用其中的对象,因此从技术上讲它尚未分配值。

Adr*_*and 5

因为const意味着对对象的引用不能更改,因此它对该对象可以执行的操作没有影响。

const arr = [];
arr.push(1); // This is allowed as you are modifying the object arr points to, not the reference pointer
arr = [...arr]; //this is an exception because you are trying to assign a new reference to the const arr
Run Code Online (Sandbox Code Playgroud)