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

如何通过用户输入的数组应用常量数组并获得总和?


用户始终输入 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) = 114


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

var arr2 = [];

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


var 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);


DIEA
浏览 81回答 4
4回答

一只斗牛犬

尝试使用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&nbsp;// 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))

Helenr

for您可以使用清晰的语法of强制执行此操作const arr = [5, 7, 3, 5, 2]const nums = [8, 3, 7, 4, 6, 5]let result = 0for (const [ key, value ] of Object.entries(arr))&nbsp; 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 =&nbsp; arr.reduce&nbsp; &nbsp; ( (sum, value, key) => sum + (value * nums[key])&nbsp; &nbsp; , 0&nbsp; &nbsp; )console.log(result) // 114

jeck猫

这是答案(请点击“运行代码片段”)如果您需要任何解释,或者这不是您要问的,请评论我的答案function getTotal() {&nbsp; const arr = [5, 7, 3, 5, 2];&nbsp; var userNumbers = document.getElementById('yourNumber').value.split('');&nbsp;&nbsp; var sum = 0;&nbsp; //itreate over your array case it is short (or a condition to itreate over the shortest one)&nbsp; for (var i = 0; i < arr.length; i++) {&nbsp; &nbsp; sum += parseInt(userNumbers[i]) * arr[i];&nbsp; }&nbsp; console.log(sum);&nbsp; document.getElementById('answer').innerHTML ='Answer will be here: '+ sum;}<html><head>&nbsp; <title>StackOverFlow &#127831;</title>&nbsp; <link rel="shortcut icon" type="image/x-icon" href="https://image.flaticon.com/icons/png/512/2057/2057586.png" /></head><body>&nbsp; <h3>Stack Over Flow &#127831;</h3>&nbsp; <input id="yourNumber" type="text" value="837465">&nbsp; <button onclick="getTotal()">get the answer</button>&nbsp;&nbsp;&nbsp; <p id="answer">Answer will be here: </p></body></html>

慕村9548890

以下作品:const arr = [5, 7, 3, 5, 2];var num = document.getElementById("yourNumber").value; //input from .htmlvar sum = 0;for (var i = 0; i< num.length-1; i++){&nbsp; //var i = 1 b/c user always enters 6&nbsp;digits, i feel this is wrong?&nbsp; &nbsp; sum += (arr[i]*parseInt(num[i]));}console.log(sum);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5