我正在尝试计算变量中“a”字母的数量,但有些东西不起作用:
js代码是:
function verChars() {
var z = document.getElementById("num").value;
var y = 0;
var x = 0;
for (x = 0; x < z.length; x++) {
if (z.substring(x) === "a") {
y++;
}
}
if (y === 0) {
alert("The string has no 'a' char.");
} else if (y === 1) {
alert("The string has a single 'a' char.");
} else {
alert("The string has "+ y +" 'a' chars.");
}
}
HTML代码是:
<input type="text" id="num" value="Some text...">
<input type="button" onClick="verChars();" value="Test!">