【问题标题】:How do I perform a calculation on each object in my array, then output that array?如何对数组中的每个对象执行计算,然后输出该数组?
【发布时间】:2019-04-28 20:22:58
【问题描述】:

我正在尝试在 Javascript (n^e mod n) 中对数组中的每个元素 e 执行计算,然后输出随后创建的新数组。我该怎么做?到目前为止,这是我想出的,但是代码不起作用。

到目前为止,这是我想通的,但代码不起作用。

function encryptText() {
  var plaintext = document.getElementById('plaintext').value;
  var n = letterValue(String(plaintext));
  ciphertext = array()
  foreach(addon_array as key => col) {
    ciphertext[key] = Math.pow(col, e) % n;
  }
  document.getElementById("output3").innerHTML = "Encrypted text = " + ciphertext;
}

我希望得到一个修改后的整数数组(密文)作为结果。谢谢

【问题讨论】:

    标签: javascript arrays rsa


    【解决方案1】:

    您可以在数组上使用 Javascript 的 map() 函数。

    const arr = [1, 2, 3];
    const newArr = arr.map(i => i * 2);
    
    // should be [2, 4, 6]
    console.log(newArr); 

    【讨论】:

      【解决方案2】:

      使用Javascriptmap函数,像这样:

      function encryptText() {
        var plaintext = document.getElementById('plaintext').value;
        var n = letterValue(String(plaintext));
        ciphertext = addon_array.map((el) => Math.pow(el, e) % n);
        document.getElementById("output3").innerHTML = "Encrypted text = " + ciphertext;
      }
      

      【讨论】:

      • 嗨,我用那个替换了代码,但我得到了这个答案:加密文本 = NaN、NaN、NaN、NaN、NaN。我将如何解决这个问题?谢谢
      • 嗨奥拉夫!仅凭您发布的代码很难分辨。你能告诉我plaintextaddon_arrayen 的值是多少吗?另外,letterValue 是做什么的?我有一种感觉,您正在尝试在字符串而不是数字上调用 Math.pow
      【解决方案3】:

      您在 javascript 中使用 php 语法 :)

      在 js 中应该是这样的

      function encryptText() {
        var plaintext = document.getElementById('plaintext').value;
        var n = letterValue(String(plaintext));
        var ciphertext = []
        for(var key in addon_array) {
          let col = addon_array[key]
          ciphertext[key] = Math.pow(col, e) % n;
        }
        document.getElementById("output3").innerHTML = "Encrypted text = " + ciphertext;
      }
      

      但如前所述,在 js 中更好的方法是使用 Array.map 函数

      function encryptText() {
        var plaintext = document.getElementById('plaintext').value;
        var n = letterValue(String(plaintext));
        var ciphertext = addon_array.map((el) => Math.pow(el, e) % n);
        document.getElementById("output3").innerHTML = "Encrypted text = " + ciphertext;
      }
      

      如果您确定 addon_array 确实是数组,而不是对象,它应该可以工作。 js 中的数组与 php 略有不同。阅读更多here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-26
        • 2019-01-17
        • 1970-01-01
        • 2021-04-08
        • 2019-07-15
        • 2021-07-13
        • 1970-01-01
        • 2019-09-26
        相关资源
        最近更新 更多