我创建了一个名为“alphabet”的常量,并将其分配给包含字母表前 5 个字母的数组。然后,我想要一个函数,该函数将向数组中的每个字符添加一个数字,以枚举它们。但是,我不希望修改原始“字母表”数组中的值,因此我在枚举函数中创建了一个“temp”变量,并且只对其进行了更改。但是,我对“temp”所做的任何更改都扩展到“字母表”。我不明白为什么,我想阻止这种情况发生。
const alphabet = ["a", "b", "c", "d", "e"];
function alphaPosition(seq) {
//'temp' gets 'seq' to avoid making changes directly on the provided argument.
let temp = seq;
//adds indexes to each element in the 'temp' array:
for (let i = 1; i <= temp.length; i++) {
temp[i - 1] = temp[i - 1] + i;
}
return temp;
}
console.log(
"Step 1. 'alphabet' array before running the 'alphaPosition' function:"
);
console.log(alphabet);
console.log(
"Step 2. This is the final value of 'temp' in 'alphaPosition' after running the function. An index has been added to every element in the array, as expected:"
);
console.log(alphaPosition(alphabet));
console.log(
"Step 3. Here's the 'alphabet' array after running 'alphaPosition'. Indexes have also been added to every element, despite not modifying the function argument directly:"
);
console.log(alphabet);
输出:
/*
-> Step 1. 'alphabet' array before running the 'alphaPosition' function:
-> ["a", "b", "c", "d", "e"]
-> Step 2. This is the final value of 'temp' in 'alphaPosition' after running the function. An index has been added to every element in the array, as expected:
-> ["a1", "b2", "c3", "d4", "e5"]
-> Step 3. Here's the 'alphabet' array after running 'alphaPosition'. Indexes have also been added to every element, despite not modifying the function argument directly:
-> ["a1", "b2", "c3", "d4", "e5"]
*/
为什么对“临时”的更改会传播为“字母表”?我希望,既然我把“字母表”定义为一个常量,那么甚至不应该修改它。此外,我从不在函数中对其进行更改。我只用它来定义“温度”。有没有办法防止这些传播的发生?
为什么使用中间变量来避免对原始数字进行更改,而不是数组?
如果对此有任何帮助或澄清,我将不胜感激。我已经将我的代码添加到这个CodePen中,以防你想调整它或尝试更多。提前感谢您的任何帮助。
DIEA
GCT1015
相关分类