在不重新设置javascript中变量的情况下,在for循环中重用函数的正确方法是什么?

时间:2019-02-08 09:37:37

标签: javascript node.js

当我尝试优化代码时遇到了这个问题。我正在尝试在代码中使用一个函数(好像我必须重复执行两次代码才能使其正常工作,因为我没有得到想要的结果):

let tmpCont = undefined;
let tmpPrice = undefined;

let evaluate = undefined;
let evaluate2 = undefined;

let cont = 0;
let tmp = true;

let cont2 = 30;
let tmp2 = false;

for (let i = 0; i < 10; i++) {
  evaluate = analize(cont, tmp);
  console.log(evaluate + "test");

  evaluate2 = analize(cont2, tmp2);
  console.log(evaluate2);
}

function analize(tmpCont, tmpPrice) {
  for (let i = 0; i < 10; i++) {
    tmpCont++;
  }
  return [tmpCont, tmpPrice];
}

我得到的结果(我不想要的):

10,truetest
[ 30, false ]
10,truetest
[ 30, false ]
10,truetest
[ 30, false ]
10,truetest
[ 30, false ]
10,truetest
[ 30, false ]
10,truetest
[ 30, false ]
10,truetest
[ 30, false ]
10,truetest
[ 30, false ]
10,truetest
[ 30, false ]
10,truetest
[ 30, false ]

我的问题是:我做错什么了吗?我知道为什么我得到了我不想要的结果,并且我认为有些东西丢失了吗?但是我必须重复代码才能得到下面的结果吗?

我想要的结果:

10,truetest
[ 40, false ]
20,truetest
[ 50, false ]
30,truetest
[ 60, false ]
40,truetest
[ 70, false ]
50,truetest
[ 80, false ]
60,truetest
[ 90, false ]
70,truetest
[ 100, false ]
80,truetest
[ 110, false ]
90,truetest
[ 120, false ]
100,truetest
[ 130, false ]

2 个答案:

答案 0 :(得分:1)

在javascript中,传递给函数的所有变量均为passed by value,并非引用。更改函数中的值不会更改传递的变量的值。您有2个选择:

  1. 传递包含计数的对象。
  2. 分配返回的值。

首先要做:

let evaluate = undefined;
let evaluate2 = undefined;

const values={cont:0, price:true};
const values2={cont:30, price:false};

for (let i = 0; i < 10; i++) {
  evaluate = analize(values);
  console.log(evaluate + " test");

  evaluate2 = analize(values2);
  console.log(evaluate2);
}

function analize(tmp) {
  for (let i = 0; i < 10; i++){
    tmp.cont++;
  }
  return [tmp.cont, tmp.price];
}

或:

let evaluate = undefined;
let evaluate2 = undefined;

let cont = 0;
let tmp = true;

let cont2 = 30;
let tmp2 = false;

for (let i = 0; i < 10; i++) {
  [cont,tmp] = analize(cont, tmp);
  console.log([cont,tmp] + " test");

  [cont2, tmp2]= analize(cont2, tmp2);
  console.log([cont2, tmp2]);
}

function analize(tmpCont, tmpPrice) {
  for (let i = 0; i < 10; i++) {
    tmpCont++;
  }
  return [tmpCont, tmpPrice];
}

答案 1 :(得分:-1)

您只需在每个for循环的末尾增加值

let tmpCont = undefined;
let tmpPrice = undefined;

let evaluate = undefined;
let evaluate2 = undefined;

let cont = 0;
let tmp = true;

let cont2 = 30;
let tmp2 = false;

for (let i = 0; i < 10; i++) {

  evaluate = analize(cont, tmp);
  console.log(evaluate + "test");

  evaluate2 = analize(cont2, tmp2);
  console.log(evaluate2);
  cont += 10 // this
  cont2 += 10 // and this 
}

function analize(tmpCont, tmpPrice) {

  for (let i = 0; i < 10; i++) {
    tmpCont++;
  }

  return [tmpCont, tmpPrice];
}