gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:38:09 28 4
gpt4 key购买 nike

<分区>

在下面的代码中,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]

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