gpt4 book ai didi

javascript - 函数应该是非破坏性的,但它正在修改我的变量

转载 作者:行者123 更新时间:2023-12-01 01:07:47 24 4
gpt4 key购买 nike

我有以下代码,它设置 special 来运行函数 convertSpecial,该函数将用提供的字符替换 array1 中的撇号。在本例中,是一个空格。由于替换字符是空格,因此它将将该元素拆分为两个,然后展平数组。然后,它将检查 special 中的任何元素是否与 array2 中的任何元素匹配。这将返回 false。然后它将用根本不包含字符的撇号替换并重新检查 array2。

convertSpecial 和变量 special 背后的想法是它应该对 array1 非破坏性,但这并没有发生,因为你可以看到:

var array1 = ["o'hara"];
var array2 = ["ohara"];
var special = '';

function convertSpecial(a,b,c) {
var aCopy = a;
for (let i = 0; i < aCopy.length; i++) {
if (aCopy[i].includes(b)) {
if (c == '') {
aCopy[i] = aCopy[i].replace(b,c);
} else {
aCopy[i] = aCopy[i].replace(b,c).split(' ');

aCopy = aCopy.flat();
}
}
}

return aCopy;
}

console.log('array1 1 = '+array1); // returns array1 1 = o'hara as expected

special = convertSpecial(array1,"'"," ");

console.log('array1 2 = '+array1); // returns array1 2 = o,hara THIS SHOULD NOT HAVE BEEN MODIFIED
console.log('special 1 = '+special); //returns special 2 = o,hara as expected

if (array2.some(v => special.includes(v)) == true) {
console.log('array1 3 = '+array1); // ignored as expected

array1 = specialDECln;
} else {
console.log('array1 4 = '+array1); //returns array1 4 = o,hara THIS SHOULD NOT HAVE BEEN MODIFIED

special = convertSpecial(array1,"'","");

console.log('array1 5 = '+array1); //returns array1 5 = o,hara THIS SHOULD NOT HAVE BEEN MODIFIED
console.log('special 2= '+special); //returns special 2 = o,hara should be ohara

if (array2.some(v => special.includes(v)) == true) {
array1 = special;
}
}

console.log(array2 == special); //returns false, should be true because expected ohara = ohara

一切都按其应有的方式运行,除了 array1 在根本不应该被修改的情况下被修改。由于它被修改,special 被设置为不正确的值。

我做错了什么以及如何解决它?

最佳答案

您需要克隆该数组以避免突变。有很多方法可以做到这一点,另一种方法是使用 Spread 语法,如下所示:

let result = [...a]; // This creates a new array with the index-values from array a.

var array1 = ["o'hara"];
var special = ''

console.log("array1 = " + array1); // returns array1 = o'hara as expected

function convertSpecial(a, b, c) { // a = array, b = character to replace, c = character to replace with
let result = [...a];
for (let i = 0; i < result.length; i++) {
if (result[i].includes(b)) {
if (c == '') {
result[i] = result[i].replace(b, c);
} else {
result[i] = result[i].replace(b, c).split(' ');
result = result.flat();
}
}
}

return result;
}

special = convertSpecial(array1, "'", " ");

console.log("array1 = " + array1); // returns array1 = o, hara but it should be o'hara

console.log("special = " + special); // returns special = o, hara as expected

关于javascript - 函数应该是非破坏性的,但它正在修改我的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55465910/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com