我正在尝试寻找解决方案:
用户被要求按顺序输入一组随机数字:
var num1 = prompt("Enter 1st set of numbers");
var num2 = prompt("Enter 2nd set of numbers");
var num3 = prompt("Enter 3rd set of numbers");
var myNumbers =[num1, num2, num3];
现在我试图比较数组每个元素中的数字总和。例如,如果 myNumbers[0] = 32,myNumber[1] = 45,则比较 5 (3+2) 和 9 (4+5) 的函数是什么?
我试图通过添加该元素中的数字来比较每个元素的总和,并返回最大的数字。因此,如果 num1= 1234,则 myNumbers[0] 的总和应为 10。通过比较,如果 num2 = 3456,则总和应为 18,函数应返回 num2。
请您参考如下方法:
var num1 = prompt("Enter 1st set of numbers");
var num2 = prompt("Enter 2nd set of numbers");
var num3 = prompt("Enter 3rd set of numbers");
// finds the sum of your array, parsing each element as an integer
var sum = function(array){
var digits = array.split("")
return digits.reduce(function(a, b) {return parseInt(a, 10) + parseInt(b, 10)})
}
var myNumbers =[num1, num2, num3]
var findLargest = function(array){
var answer
var largest = 0
array.forEach(function(input){
// check if this is the largest sum
if (sum(input) == largest){
// check if there is already a running set of equal sums
if (typeof(answer) == Object) answer.push(input)
// create set of equal sums if not
else answer = [answer, input]
}
else if (sum(input) > largest) {
largest = sum(input)
answer = input
}
})
return answer
}
alert(findLargest(myNumbers))
https://jsfiddle.net/gmebk2Ly/7/
这还会检查是否有多个输入相等