【发布时间】: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