【问题标题】:Javascript: Dynamic Variables in For LoopJavascript:For循环中的动态变量
【发布时间】:2019-02-05 11:56:28
【问题描述】:

我是 javascript 初学者,需要您的帮助!非常感谢您的帮助!

cell_660 = cell_638;
cell_659 = cell_637;
...

它就是这样工作的。我现在想每秒对所有 660 个变量执行此操作,以将它们的值更改为名称末尾有数字(自己的数字 -22)的变量的值。当然不用写660行代码!到目前为止我尝试过这个:

var count = 660;

setInterval(function(){

for(var i=1;i<=660;i++){
    'cell_' + count = 'cell_' + eval(count - 22);
    count--;
}
count=660;

},1000);

我该如何正确地写这个?我已经阅读了关于 window['cell_' + count] - 但我不想每秒创建 660 个新变量。我想每秒更改 660 个变量的值。

【问题讨论】:

  • 这不是创建新变量。
  • 括号语法创建或更新具有动态名称的变量。此外,您不需要eval:只需'cell_' + (count - 22)
  • 谢谢@HereticMonkey - 我会按照你描述的方式再试一次 - 但javascript不会解释 >>>> 'cell_' + 变量
  • 是的,您需要使用以前的 window['cell_' + count] 代码。不过,您应该首先阅读这个问题的答案;拥有 600 多个变量绝对是设计选择错误的标志。
  • 我了解您正在学习,但正如您所见,以下所有答案都指向使用数组。如果您打算进行任何严肃的编程,您需要学习最佳实践并计划好您的代码(甚至用纸和铅笔),然后再开始在计算机上进行任何操作。相信我,您会非常感激它为避免思考和流程错误而节省的时间。

标签: javascript jquery variables for-loop dynamic


【解决方案1】:

您需要每秒更改 660 个变量吗?如果您只创建一个数值变量,当您显示或使用数组值时,它会保持“数组中的起始位置”的位置?

var cells = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

var currentStart = 0;

// create an interval to modify currentStart
setInterval(function () {
  currentStart = (currentStart + 22) % cells.length;
}, 1000);

function doSomething() {
  // display contents starting at currentStart
  var msg = "";
  for (var i = 0; i < cells.length; i++) {
    var index = (i + currentStart) % cells.length;
    // do something with cells[index]
    msg += "," + cells[index];
  }
  console.log(msg);
}

document.querySelector("#thing").addEventListener("click", doSomething);
&lt;button id='thing'&gt;click me&lt;/button&gt;

【讨论】:

    【解决方案2】:

    带有数组

    用数组代替这么多变量怎么样?

    let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    function moveArrElem() {
      // loop all elements of the array
      // using arr.map give us a buffer so current index are keeped while doing the modification
      arr = arr.map((_, i) => {
        
        // get the new index and make it valid if necessary
        let newIndex = i - 2; 
        if (newIndex < 0) {
          newIndex += arr.length
        }
        return arr[newIndex]
      })
      console.log(arr)
    }
    
    console.log(arr)
    setInterval(moveArrElem, 2000)

    关于window['cell_' + count]它不会每次都创建一个新变量,事实上var test = 42等于window["test"] = 42如果你在全局范围内(在任何函数和其他块之外)

    所以window['cell_' + count] 只会修改 var 的值

    var test = 42
    console.log(window["test"])

    最后尽量避免eval,它很慢而且通常是一个安全问题

    一些(我就是其中之一)致电eval 几乎总是表明其他地方存在误解


    无数组

    由于OP在评论中告诉他他还没有学习数组,这是一个没有数组的解决方案

    let quantity = 660
    
    // declaring the 660 vars
    for (let i = 0; i < quantity; i++) {
      window["cell_" + i] = i;
    }
    
    function moveCells() {
      // need some tmp vars
      for (let i = 0; i < quantity; i++) {
        window["tmp_" + i] = window["cell_" + i];
      }
      
      for (let i = 0; i < quantity; i++) {
        let newIndex = i - 22
        if (newIndex < 0) {
          // equals to : newIndex = newIndex + quantity
          newIndex += quantity
        }
        window["cell_" + newIndex] = window["tmp_" + i];
      }
    
      // displaying 660 items would take to much time and place
      console.log("cell_42 : " + cell_42)
      console.log("cell_43 : " + cell_43)
      console.log("cell_44 : " + cell_44)
      console.log("cell_45 : " + cell_45)
      console.log("cell_46 : " + cell_46)
    }
    
    console.log("cell_42 : " + cell_42)
    console.log("cell_43 : " + cell_43)
    console.log("cell_44 : " + cell_44)
    console.log("cell_45 : " + cell_45)
    console.log("cell_46 : " + cell_46)
    
    setInterval(moveCells, 1000)

    【讨论】:

    • 感谢您的回答!我还没有学会如何使用数组,对函数等也知之甚少,所以很遗憾你的答案对我来说太难理解了
    • @javascriptLearner 数组是需要的,如果你想像在这种情况下使用大量变量,我会在我的答案末尾添加一种不使用数组的方法;)
    • @javascriptLearner 添加了一个没有数组的解决方案
    • 谢谢我在您的帮助下解决了我的问题,非常感谢您提供没有数组的解决方案!我可以给你一个“最佳答案”的标题吗?我是stackoverflow的新手-但是非常感谢
    • @javascriptLearner 您可以通过单击答案左上角的绿色勾号将答案标记为accepted
    【解决方案3】:

    在我给你答案之前,我首先要指出这是糟糕的代码实践。您永远不需要 660 个变量!无论您尝试做什么,都可以通过数组来完成。话虽如此,以下是您将如何进行这项工作,以及您应该如何在下面实际执行此操作。我强烈建议您考虑使用数组方法!

    setInterval(function() {
      for(var i = 660; i > 22; i--) {
        window['cell_' + i] = window['cell_' + (i - 22)];
      }
    },1000);
    

    现在这里有一些更符合您实际应该做的事情。

    var cells = [/* 660 elements */];
    setTimeout(function() {
      for(var i = 22; i < 660; i++) {
        cells[i] = cells[i - 22];
      }
    }, 1000);
    

    事实上,通过这个方法,你可以用 ES6 中新的Array#copyWithin 方法在一行中完成所有事情。

    const cells = [/* 660 elements */];
    setTimeout(() => {
      cells.copyWithin(22);
    }, 1000);
    

    【讨论】:

    • 没有数组的解决方案现在为我做了,我解决了我的问题 - 我正在学习如何在几个月内使用数组,我永远不会在任何与工作相关的事情上使用超过 20 个变量 - 这是只是一个实验,别担心 - 感谢您非常明确和准确的回答
    猜你喜欢
    • 2016-07-19
    • 1970-01-01
    • 2012-05-28
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多