我想将我的简单python代码转换为JavaScript。在JavaScript中,我注意到for循环基于C和C ++语法,因此
for( INITIALIZE; BOOLEAN EXPRESSION; ACTION)
{
STATEMENT;
STATEMENT;
}
我有这个简单的代码(只计算字符串中的字符)我想要转换为JavaScript
def countLetter(word, letter):
count = 0
for character in word:
if letter == character:
count = count + 1
return count
在JavaScript中
function countLetter(word, letter) {
for (var characters in word){...}
答案 0 :(得分:1)
尝试:
var count = 0;
for(var i=0; i<word.length; i++) {
if(word.charAt(i) == letter) {
count++;
}
}
in
运算符在JavaScript中的行为有所不同。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt
答案 1 :(得分:1)
你也可以在javascript中使用substr
:
var count = 0;
for(var i=0; i<word.length; i++) {
if(word.substr(i,1) == letter) {
count++;
}
}