为了账号安全,请及时绑定邮箱和手机立即绑定

如何将常量数组与用户输入数组相乘?

如何将常量数组与用户输入数组相乘?

DIEA 2023-10-30 15:07:40
如何通过用户输入的数组应用常量数组并获得总和?用户始终输入 6 位数字,但常量为 5 位数字例子[5, 7, 3, 5, 2] 是我要乘以的常量数组用户输入 837465变成 [8, 3,7,4,6,5] (但我希望 5 被忽略)乘以常量数组(不包括最后一个元素)并得到总和:(8*5)+ (3*7) + (7*3) + (4*5)+ (6*2) = 114const arr = [5, 7, 3, 5, 2];var arr2 = [];var num = parseInt(document.getElementById("yourNumber").value); //input from .htmlvar sum = 0;for (var i = 1; i< num.length; i++){  //var i = 1 b/c user always enters 6 digits, i feel this is wrong?    arr2.push(parseInt(num[i]));    sum += (arr2[i]*arr[i]);}console.log(sum);
查看完整描述

4 回答

?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

尝试使用const input = '837465'.split('')或准备好数组const input = [8, 3, 7, 4, 6, 5]和reduce()方法来求和数组。当原始数组中有元素时,reduce 就会起作用


const array = [5, 7, 3, 5, 2]

const input = '837465'.split('')

//or 

// const input = [8, 3, 7, 4, 6, 5]


const summ = (input) => array.reduce((acum, rec, index) => acum + (rec * input[index]), 0)


console.log(summ(input))


查看完整回答
反对 回复 2023-10-30
?
Helenr

TA贡献1780条经验 获得超3个赞

for您可以使用清晰的语法of强制执行此操作


const arr = [5, 7, 3, 5, 2]

const nums = [8, 3, 7, 4, 6, 5]


let result = 0


for (const [ key, value ] of Object.entries(arr))

  result = result + (value * nums[key])


console.log(result) // 114

或者您可以使用声明式地执行此操作Array.prototype.reduce-


const arr = [5, 7, 3, 5, 2]

const nums = [8, 3, 7, 4, 6, 5]


const result =

  arr.reduce

    ( (sum, value, key) => sum + (value * nums[key])

    , 0

    )


console.log(result) // 114


查看完整回答
反对 回复 2023-10-30
?
jeck猫

TA贡献1909条经验 获得超7个赞

这是答案(请点击“运行代码片段”)


如果您需要任何解释,或者这不是您要问的,请评论我的答案


function getTotal() {

  const arr = [5, 7, 3, 5, 2];

  var userNumbers = document.getElementById('yourNumber').value.split(''); 

  var sum = 0;

  //itreate over your array case it is short (or a condition to itreate over the shortest one)

  for (var i = 0; i < arr.length; i++) {

    sum += parseInt(userNumbers[i]) * arr[i];

  }


  console.log(sum);

  document.getElementById('answer').innerHTML ='Answer will be here: '+ sum;

}

<html>


<head>

  <title>StackOverFlow &#127831;</title>

  <link rel="shortcut icon" type="image/x-icon" href="https://image.flaticon.com/icons/png/512/2057/2057586.png" />

</head>


<body>

  <h3>Stack Over Flow &#127831;</h3>


  <input id="yourNumber" type="text" value="837465">


  <button onclick="getTotal()">get the answer</button>

  

  <p id="answer">Answer will be here: </p>


</body>


</html>


查看完整回答
反对 回复 2023-10-30
?
慕村9548890

TA贡献1884条经验 获得超4个赞

以下作品:


const arr = [5, 7, 3, 5, 2];

var num = document.getElementById("yourNumber").value; //input from .html


var sum = 0;

for (var i = 0; i< num.length-1; i++){  //var i = 1 b/c user always enters 6 

digits, i feel this is wrong?

    sum += (arr[i]*parseInt(num[i]));

}


console.log(sum);


查看完整回答
反对 回复 2023-10-30
  • 4 回答
  • 0 关注
  • 126 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信