当函数在不同的声明变量上运行时,为什么输入会改变?

时间:2018-03-31 21:23:42

标签: javascript

在下面的代码中,operatorSequence函数应该使用变量" input"并且" inputArray"但是当函数运行时,inputArray(" a")会被更改。

导致此问题的原因是什么,以及如何修复以使inputArray不被更改?



//factorial in maths
function factorial(input) {
  if (input == 0) return 1;
  if (input > 0) return input * factorial(input - 1);
}
//slices an index from an array
function sliceIndex(array, index) {
  let temp = array.slice(0, index);
  temp.push.apply(temp, array.slice(index + 1));
  return temp;
}

//operator sequence
function operatorSequence(inputArray, operatorArray, det) {
  //the function should run on the "input" variable
  let input = inputArray;
  //det determines bracket position
  //according to the bracket position, two input indices are merged into one, and an operator is deleted
  while(operatorArray.length > 0) {
    let temp1 = factorial(operatorArray.length - 1);
    let temp2 = Math.floor(det / temp1);
    input[temp2] = operatorArray[temp2](input[temp2], input[temp2 + 1]);
    operatorArray = sliceIndex(operatorArray, temp2);
    input = sliceIndex(input, temp2 + 1);
    det -= temp1 * temp2;
  }
  return input[0];
}

const a = [1, 8, 3, 4];
let b = [(a, b) => a + b, (a, b) => a - b, (a, b) => a * b];
console.log(operatorSequence(a, b, 0));
console.log(a);
//24
//[9, 8, 3, 4]




1 个答案:

答案 0 :(得分:1)

let input = inputArray;

将数组赋值给另一个变量不会产生带有值的新数组。相反,它使用与原始数组相同的对象引用。

稍后,您可以指定值

input[temp2] = operatorArray[temp2](input[temp2], input[temp2 + 1]);

到数组inputinputArray作为原始数组a

您可以使用Array#slice

处理数组的浅表副本
let input = inputArray.slice();