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))
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
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 🍗</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 🍗</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>
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);
- 4 回答
- 0 关注
- 121 浏览
添加回答
举报