【问题标题】:Re-feeding a variable into a looped function将变量重新输入循环函数
【发布时间】:2017-04-26 00:08:52
【问题描述】:

我正在尝试制作一个简单的程序,用于多次在 base64 中进行编码(并非出于任何特定原因,只是作为示例和实践)。不过,我遇到了很多麻烦,可能是因为我没有喝足够(或可能喝太多)咖啡。

i 等于times 之前,我似乎无法弄清楚如何将我的变量(文本)重新输入到对其进行编码的函数中

我们将不胜感激!

<html>
    <head>
        <script>
        function encodeThis(text,times) {
            var toEncode = text;
            for (var i = 0; i < times, i++) {
                btoa(toEncode);
            }
            document.getElementById("result").value = toEncode;
        }
        </script>
    </head>
    <body>
        <b>Text to Encode</b><br/>
        <input type="text" id="encode"><br/>
        <b>Number of Times to Encode (Integers Only)<br/>
        <input type="text" id="times">
        <button type="submit" onclick="encodeThis(encode,times)">Test</button>
        <br/>
        <br/>
        <b>Result</b><br/>
        <input type="text" id="result">
    </body>
</html>

我是否需要在该函数中放置一个函数来重新输入变量?

【问题讨论】:

  • 我觉得应该是toEncode = btoa(toEncode);

标签: javascript function loops


【解决方案1】:

您需要将编码结果分配回变量。

function encodeThis(text, times) {
  var toEncode = text;
  for (var i = 0; i < times, i++) {
    toEncode = btoa(toEncode);
  }
  document.getElementById("result").value = toEncode;
}

但就您示例中的整体代码而言,您还需要实际从#encode#times 元素中获取文本,并修复for 循环中的语法错误。

所以

function encodeThis(text, times) {
  var toEncode = text.value, // read the value from the encode input element
    numTimes = parseInt(times.value, 10); // read the value from the times element and convert to number

  for (var i = 0; i < numTimes; i++) {
    toEncode = btoa(toEncode);
  }
  document.getElementById("result").value = toEncode;
}
<b>Text to Encode</b><br/>
<input type="text" id="encode" /><br/>
<b>Number of Times to Encode (Integers Only)</b><br/>
<input type="text" id="times" />
<button type="submit" onclick="encodeThis(encode,times)">Test</button>
<br/>
<br/>
<b>Result</b><br/>
<input type="text" id="result">

【讨论】:

  • @MarkisCook 我刚刚添加了一个更新,修复了一些更基本的问题。
  • 这绝对有效。非常感谢。我不知道您必须输入 text.value 和 times.value 来记录信息!此外,我似乎也有很多针对我的合成器错误。很好的答案,非常感谢!
猜你喜欢
  • 2019-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多