我有以下代码,将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/

10-11 12:53