比较数组内的值之和以确定哪个是最大的 [英] Comparing sums of values inside array to determine which is the largest

查看:52
本文介绍了比较数组内的值之和以确定哪个是最大的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在应对编码方面的挑战,并相信我已经接近解决方案,但目前仍处于困境,不胜感激.我正在尝试构建一个函数,该函数可以采用一组数字(包括破折号的信用卡号),比较每个数字的总和,并返回最高的信用卡号.解决方案必须使用Javascript.该函数当前返回"undefined".预先感谢您的帮助!

I am working on a coding challenge and believe I am close to a solution, but am currently stuck and would appreciate some insight. I am trying to build a function that can take a set of numbers (credit card numbers including dashes), compare the sum of each number, and return the highest credit card number. The solution must utilize Javascript. The function is currently returning "undefined". Thanks in advance for any help!

function highestCredit(creditArray){
  var highSum = 0;
  var highIndex = 0;
  var sum= 0;
  //loop through each value in the array
  for (i = 0; i < creditArray.length; i++) {
    //loop that disregards dashes and adds up the sum of a single credit card number
    for (a = 0; a < creditArray[i.length]; a++) {
      if(isNaN(creditArray[i].charAt(a)) === false){
          sum += parseInt(creditArray[i].charAt(a));
      }
    }
    //compare current sum to highest sum, update the index if there is a new high number
    if (sum >= highSum) {
      highSum = sum;
      sum = 0;
      highIndex = i;
    }
  }
  return creditArray[i];
}

console.log(highestCredit(['4916‐2600‐1804‐0530', '4779‐252888‐3972', '4252‐278893‐7978' ,'4556‐ 4242‐9283‐2260']));

推荐答案

您遇到了一些错误,请参见工作示例

You had some errors, see working example

  function highestCredit(creditArray) {
    var highSum = 0;
    var highIndex = 0;
    var sum = 0;
    for (i = 0; i < creditArray.length; i++) {
        for (a = 0; a < creditArray[i].length; a++) { // error with length
            if (isNaN(creditArray[i].charAt(a)) === false) {
                sum += parseInt(creditArray[i].charAt(a), 10);
            }
        }
        if (sum >= highSum) {
            highSum = sum;
            sum = 0;
            highIndex = i;
        }
    }
    return creditArray[highIndex]; // should return 'highIndex', not 'i'
}

document.write(highestCredit(['4916‐2600‐1804‐0530', '4779‐252888‐3972', '4252‐278893‐7978' ,'4556‐ 4242‐9283‐2260']));

这篇关于比较数组内的值之和以确定哪个是最大的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆