【问题标题】:Accessing indexes of a string inside an array and taking the sum访问数组中字符串的索引并求和
【发布时间】:2016-01-04 21:42:53
【问题描述】:

好的,所以我正在尝试访问该数组内部字符串中的每个单独的数字。

var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
var str = "";
for (i=0; i<array.length; i++) {
  str = array[i];
}

问题在于这是输出:'999-992-1313'

而不是第一个元素数组[0]:'818-625-9945'

当我尝试使用嵌套的 for 循环遍历字符串中的每个元素时,我无法说明这些元素。

var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
for (i=0; i<array.length; i++) {
  for (j=0; j<array[i].length; j++) {
    console.log(array[i][j]);
  } 
}

我不知道如何访问字符串数组[i] 中的每个单独的数字。我想找到一种方法来制作一个计数器,这样如果我遇到数字“8”,我就会在总分上加 8,这样我就可以对每个单独的字符串元素求和,看看哪个数字的总和最高。

var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
for (i=0; i<array.length; i++) {
  for (j=0; j<array[i].length; j++) {
    if (array[i](j).indexOf('8') !== -1) {
      // add one to total score
      // then find a way to increase the index to the next index (might need help here also please)
    }
  }
}

【问题讨论】:

  • 你想达到什么目标?
  • 您的第一段代码按预期工作,所以我不确定您的问题是什么 (jsfiddle.net/vr34gqyw)
  • 您可以在连字符 (-) 上拆分每个成员,拆分每个数字并添加位,例如'818'.split('').reduce(function(a, b){return +a + +b}) 返回17。您想添加"818-625-9945" 中的所有数字还是仅添加每个序列中的数字,例如"818", "625", "9945"?
  • 在我看来,您正在寻找最多 8 的数字。那将是 888-222-2222,这就是您要寻找的答案吗?

标签: javascript arrays string indexing indexof


【解决方案1】:

这对你有用。它使用了Array.prototype.reduce()Array.prototype.map()String.prototype.split()

这个提议遍历给定的数组并拆分每个字符串,然后过滤得到的数组并检查'8'。返回的数组作为计数,与reduce的前一次迭代的返回值相加 - 并返回。

var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'],
    score = array.reduce(function (r, a) {
        return r + a.split('').filter(function (b) { return b === '8'; }).length;
    }, 0);

document.write('Score: ' + score);

在每个字符串上计算所有'8' 的建议方法:

var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'],
    score = array.map(function (a) {
        return a.split('').filter(function (b) { return b === '8'; }).length;
    });

document.write('Score: ' + score);

【讨论】:

  • array -&gt; scalar 转换的更自然(主观)构造是Array.prototype.reduce。这样你就切换回纯函数:-)
  • 仅代码答案没有那么有用。您需要解释它是如何工作的以及它为什么回答 OP 的问题(不清楚)。另外,也不需要 map
  • 我仍然不明白这是如何回答这个问题的。我认为 OP 想要其中 8 最多的数字(但我不确定),即 888-222-2222,但 OP 说结果应该是 818-625-9945。在这种情况下,您可以在 8 上使用 reduce 和 match,获得最多匹配的那个获胜。
  • @RobG,所以任何答案都是猜测,操作人员想要什么。
  • 是的,您可以猜测(或两个),但首选策略是在明确 OP 想要什么之前不回答问题。
【解决方案2】:

实际上,重新阅读您的问题让我对您想要什么有了更好的了解。您只是想计算和检索每个字符串的 8 数,以及数组中的哪个索引符合这个最大 8 值。此函数检索在数组中找到该值的索引、找到 8 的次数以及该结果的字符串值是什么。 (或者返回一个空对象,以防你给出一个空数组)

您可以轻松做到这一点:

'use strict';
var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'];

function getHighestEightCountFromArray(arr) {
  var max = 0,
    result = {};
  if (arr && arr.forEach) {
    arr.forEach(function(value, idx) {
      var cnt = value.split('8').length;
      if (max < cnt) {
        // found more nr 8 in this section (nl: cnt - 1)
        max = cnt;
        // store the value that gave this max
        result = {
          count: cnt - 1,
          value: value,
          index: idx
        };
      }
    });
  }
  return result;
}

console.log(getHighestEightCountFromArray(array));

这里唯一的一点是,当找到相等数量的计数时,它仍然会使用找到的第一个,在这里你可以决定哪个“最大” 应该是首选(数组中的第一个,或者数组中最新/最新的)

我不确定您遗漏了哪些金额,但您可以通过以下方式完成。

我首先循环遍历数组中的所有项,然后使用String.prototype.split 函数将单个数组项拆分为一个数组,然后该数组将包含 ['818', '625', '9945']。然后对于每个值,您可以重复相同的样式,nl:拆分您收到的值,然后遍历所有单个值。然后使用Number.parseInt 将它们转换为数字,然后将所有值一起计算。

肯定有更短的方法,但这是你可以做到的方法

'use strict';

var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'],
    sumPerIndex = [],
    totalSum = 0;

array.forEach(function(item, idx) {
  var values = item.split('-'), subArray = [], itemSum = 0;
  values.forEach(function(value) {
    var singleItems = value.split(''),
        charSum = 0;
    singleItems.forEach(function(char) {
      charSum += parseInt(char);
    });
    itemSum += charSum;
    subArray.push(charSum);
    console.log('Sum for chars of ' + value + ' = ' + charSum);
  });
  sumPerIndex.push(subArray);
  totalSum += itemSum;
  console.log('Sum for single values of ' + item + ' = ' + itemSum);
});
console.log('Total sum of all elements: ' + totalSum);
console.log('All invidual sums', sumPerIndex);

【讨论】:

  • 您可以通过var charSum = split(/-|\s*/.reduce(function(a,b) return +a + +b)) 为自己保存一次迭代。但是,尚不清楚 OP 想要什么,因此这是否真的回答了这个问题是没有实际意义的。
  • @RobG: 是的,这就是为什么我选择了一个相当长的回复形式来展示他可以使用哪些方法:D 也许我应该多评论一下我的代码,但我想我们会看到OP想要什么
猜你喜欢
  • 2017-12-01
  • 1970-01-01
  • 2019-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-10
  • 2021-12-06
  • 1970-01-01
相关资源
最近更新 更多