来自codewars的Javascript索引

javascript indexes from codewars

本文关键字:索引 Javascript codewars 来自      更新时间:2023-09-26

我正在处理以下代码战问题。问题是这样的:

指令

写一个函数大写,接受一个字符串(单词)作为论点。函数必须返回一个包含字符串中所有大写字母的索引。

例子

测试。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]。有办法解决这个问题吗?

word.indexOf(word[i])返回第一个索引,您应该简单地将i推入数组。

说出来

ara.push(i)

代替

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

当您输入word.indexOf(word[i]))时,它将返回获得word[i]的第一个index。所以对于L它给出了2

你可能会觉得上面的解决方案令人满意,但我认为我会在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