来自 Codewars 的 JavaScript 索引

问题描述 投票:0回答:3

我正在解决以下代码战争问题。问题是这样的:

使用说明

编写一个大写函数,将单个字符串(单词)作为 争论。这些函数必须返回一个有序列表,其中包含 字符串中所有大写字母的索引。

示例

Test.assertSimilar( 大写字母('CodEWaRs'), [0,3,4,6] );

我的解决方案是:

function capitals(word){
  var ara = []
  for(var i = 0; i < word.length; i++){
    if(word[i] == word[i].toUpperCase()){
      ara.push(word.indexOf(word[i]))
    }
  }
 return ara
}

每当我向代码传递字符串时,代码都可以正常工作。我遇到的唯一问题是我在重复拼写时得到相同的索引。例如,

capitals("HeLLo")
返回
[0, 2, 2]
而不是
[0, 3, 4]
。 有什么办法可以解决这个问题吗?

javascript arrays indexof
3个回答
1
投票

word.indexOf(word[i])
返回 first 索引,您只需将
i
推入数组即可。


1
投票

说这个

ara.push(i)

而不是

ara.push(word.indexOf(word[i]))

当您说

word.indexOf(word[i]))
时,它将返回第一个
index
,并在其中获得
word[i]
。所以对于两个
L
来说都是 2.


0
投票

您可能会发现上述解决方案令人满意,但我想我会在 ES2015 中提供更实用的方法。

const capitals = word => word.split('') // split word into an array

  .map((letter, idx) => letter === letter.toUpperCase() ? idx : false)
  // return a new array that gives the index of the capital letter

  .filter(num => Number.isInteger(num));
  // filter through each item in the new array and return 
  // a newer array of just the index values
© www.soinside.com 2019 - 2024. All rights reserved.