【问题标题】:Look at the first letter of each string in an array in javascript在javascript中查看数组中每个字符串的第一个字母
【发布时间】:2017-12-11 22:46:15
【问题描述】:

我正在尝试评估天气用户输入字符串中的任何单词都以“@”开头。

我首先将输入字符串分解为单词数组。 然后遍历每个单词,查看第一个字母,看它是否为“@”。

我不明白为什么 charAt() 似乎返回错误。

<!DOCTYPE html>
<html>
<body>

<input id="txt" type="textarea" />
<button onclick="myFunction()">Try it</button>



<script>
function myFunction (){
  var text = document.getElementById('txt').value;
  var inputArray = [text.split(" ")];
  console.log(inputArray);

  for(i=0; i < inputArray.length; i++){
    console.log(inputArray[i]);
    if(inputArray[i].charAt(0) === '@'){
      console.log("its an at symbol");
    } else{
      console.log("nope");
    }
  }
}
</script>
</body>
</html>

【问题讨论】:

  • text.split(" ") 已经返回一个数组。你为什么要把它包起来?
  • const symbols = text.match(/@\w+/) || [];

标签: javascript charat


【解决方案1】:

var inputArray = [text.split(" ")]; 行似乎是罪魁祸首。 text.split(" ") 将返回一个数组,因此通过将该语句包装在方括号中,您将获得一个数组,其第一个索引是您要查找的数组。

因此,for 循环中的inputArray[i] 实际上是在寻找对字符串数组而不是字符串本身执行charAt(0)

【讨论】:

  • 谢谢你!这完全有道理并且有效。我认为它需要明确地放入一个数组中。
  • 没问题!很高兴能提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-03
  • 2018-06-27
  • 2022-08-23
  • 2018-09-18
  • 2020-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多