比较数组中元素的和以确定哪个是最高的

Comparing sums of elements within an array to determine which is the highest

本文关键字:数组 元素 比较      更新时间:2023-09-26

我试图在Javascript中创建一个函数,该函数将采用数字数组(特别是电话号码)的每个元素,并确定哪个元素具有最高的总和。我已经达到了一个我感到相当失败的地步,但我认为我已经非常接近了。谁能给点指导?这是我目前所看到的:

function highest(inputArray) {
  var sum = 0;
  var currentHighest = 0;
  var largest = 0;

我设置了将要使用的变量,然后创建了一个for循环来遍历数组中的每个元素。

  for (a = 0; a < inputArray.length; a++)
    var tempArray = inputArray[a].replace(/'D/g,'');

创建一个占位符字符串来删除元素中的所有非整数,然后创建一个函数来对元素中的所有数字求和。

    function sumDigits(str) {   
        for (i = 0; i < str.length; i++) {
                sum += parseInt(str.charAt(i));
        return sum;
        }
    }

然后创建一个if语句,测试当前元素的和是否大于或等于和最高的元素。

    if (sumDigits(tempArray) >= currentHighest) {
          currentHighest = sum;
          largest = inputArray[a];
          return largest;
        }
        else {
            return largest;
        }
    }
var newArray = ['123-456-7777', '963-481-7945', '111-222-3333'];
console.log(highest(newArray));

下面是整个代码块:

function highest(inputArray) {
  var sum = 0;
  var currentHighest = 0;
  var largest = 0;
  for (a = 0; a < inputArray.length; a++)
    var tempArray = inputArray[a].replace(/'D/g,'');
    function sumDigits(str) {   
        for (i = 0; i < str.length; i++) {
                sum += parseInt(str.charAt(i));
        return sum;
        }
    }
    if (sumDigits(tempArray) >= currentHighest) {
          currentHighest = sum;
          largest = inputArray[a];
          return largest;
        }
        else {
            return largest;
        }
    }
}
var newArray = ['123-456-7777', '963-481-7945', '111-222-3333'];
console.log(highest(newArray));

如果有帮助,当我运行代码时,我得到"未定义"作为结果。事先感谢您的协助。

如果我正确地解释了这个问题(将电话号码的每个数字相加,然后打印最大的结果),您可以这样完成:

//Define an array of phone numbers
var numbers = ['123-456-7777', '111-222-3333', '963-481-7945'];
//Map takes an array, does something with each element, then returns that result
var sums = numbers.map(function (m) {
    //In this case, we return an object containing the original number, and a score
    return {
        number: m,
        //The score is calculated by adding up each number.  The match expression creates an array of all terms (g modifier) matching the expression.  'd matches a single digit, so we end up with an array of each digit in the number.
        //Reduce applies a function to each item in an array, and adds them up
        score: m.match(/'d/g).reduce(function (p, c) {
            //This looks like magic, but the + before p and c coerces them to numbers (they're strings right now, since match returns an array of strings)
            //Both numbers are then added
            return +p + +c;
        })
    }
}).sort(function (a, b) {
    //Now that we have the scores of all numbers, we can sort the array to find the highest score
    //To be honest, sort() is mostly trial and error for me to find which values to return 1 and -1 for
    if (a.score < b.score) return 1;
    if (a.score > b.score) return -1;
    return 0;
});
//All together, without comments:
sums = numbers.map(function (m) {
    return {
        number: m,
        score: m.match(/'d/g).reduce(function (p, c) {
            return +p + +c;
        })
    }
}).sort(function (a, b) {
    if (a.score < b.score) return 1;
    if (a.score > b.score) return -1;
    return 0;
});
console.log(sums);
document.write("Number with the highest score: " + sums[0].number);
document.write("<br>");
document.write("It's score is " + sums[0].score);

将金额最大的数字打印到控制台。这些数字的总和也可以在score属性返回的对象中使用。

在您的代码中,您没有在这里初始化sum变量,并且您过早地在此函数中返回sum值:

function sumDigits(str) {   
    for (i = 0; i < str.length; i++) {
        sum += parseInt(str.charAt(i));
        return sum;
    }
}

应该是这样的:

function sumDigits(str) {   
    var sum = 0;
    for (i = 0; i < str.length; i++) {
        sum += parseInt(str.charAt(i), 10);
    }
    return sum;
}

如果不把所有的代码放在一个块中,我们就看不到其他地方出了什么问题,所以我们可以看到不同的部分是如何相互调用和交互的。


这里有一个更简洁的解决方案(假设你试图将每个电话号码的数字相加):

var phoneNumbers = ["123-456-7890", "982-111-9999"];
var sums = phoneNumbers.map(function(p) {
    return p.match(/'d/g).reduce(function(sum, num) {
        return sum + parseInt(num, 10);
    }, 0);
});
var maxSum = Math.max.apply(Math, sums);
// output results in the snippet window                    
document.write("sums = " + JSON.stringify(sums) + "<br>");
document.write("maxSum = " + maxSum + "<br>");

下面是它的工作原理:

  1. 在电话号码数组上运行.map(),目标是返回一个总和数组。
  2. .map()中搜索所有数字,然后在结果数组上运行.reduce()以累积总和。
  3. 然后,为了获得sums数组中的最大值,使用Math.max(),它可以接受整个数组并为您做最大的工作。