返回数组中最大和的索引

时间:2017-03-21 19:11:49

标签: javascript arrays

在JavaScript方面,我是一个新手。我正在研究一些编码问题,而且我遇到了一堵墙。这是我到目前为止遇到麻烦的代码:

function creditCardTest (creditCardNumbers) {
var creditCardNumbers = [
                                            '7629-1648-1623-7952', 
                                            '4962-1694-2293-7910', 
                                            '9999-9999-9999-9999', /*For test purposes*/
                                            '4921-2090-4961-7308'
                                            ]
var sumArray = [ ]; //parallel to creditCardNumbers array
var largestValue = 0;
var locationOfLargest = 0;
var itemSum = 0;

for(var i = 0; i < creditCardNumbers.length; i++) {

    var creditCardItem = creditCardNumbers [ i ];
    /*console.log(creditCardItem); For test purposes*/
    itemSum = 0; //required for functionality

    for (var j = 0; j < creditCardItem.length; j++) {

        var stringChar = creditCardItem.charAt( j );
        /*console.log(stringChar); For test purposes*/

            if ( stringChar >= '0' && stringChar <= '9' ) {
                itemSum += parseInt(stringChar);
                /*console.log(parseInt(stringChar)); For test purposes*/
            }

    }

    sumArray[ i ] = itemSum;
    console.log(sumArray[ i ]); /*required for functionality*/

}

if (!largestValue || sumArray[ i ] > largestValue) {
largestValue = sumArray[ i ];
locationOfLargest = i;
}

console.log(locationOfLargest);

}

creditCardTest();

我希望返回一个数组中最大的索引,但我只得到了第0个索引。有什么输入吗?

2 个答案:

答案 0 :(得分:0)

这是一个小fiddle

&#13;
&#13;
var largestValue = 0,
    locationOfLargest = 0,
    sumArray = [1, 100, 909, 8, 91098, 923823];
    for (var i = 0; i < sumArray.length; i++) {
      if (!largestValue || sumArray[i] > largestValue) {
        largestValue = sumArray[i];
        locationOfLargest = i;
      }
    }

console.log(locationOfLargest, largestValue);
&#13;
&#13;
&#13;

甚至更快的解决方案:

&#13;
&#13;
var arr = [1, 100, 909, 8, 91098, 923823],
        index = arr.indexOf(Math.max.apply(Math, arr));
        console.log(index);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用分步方法

  • 获取第一个数字数组
  • 添加数字
  • 获取最大总和的索引。

var data = ['7629-1648-1623-7952', '4962-1694-2293-7910', '9999-9999-9999-9999', '4921-2090-4961-7308'],
    index = data.
        map(a => a.match(/\d/g)).
        map(a => a.reduce((a, b) => +a + +b)).
        reduce((r, a, i, aa) => !i || aa[r] < a ? i : r, -1);

console.log(index);
.as-console-wrapper { max-height: 100% !important; top: 0; }

相关问题