I have a question concerning javascript. I have created a function which prompts the user to enter a string, and once the string is entered will perform a for loop to go through the entire length of the string, looking for the character "B" and then return the number of "B"s found in the result variable. As far as my knowledge, I feel that the code I have should work, however not matter how many "B" are present within my code, the function consistently returns 2. Any ideas on why this would be happening
function countBs(string) {
var result = 1;
var string = prompt("Please Enter a String");
for (count = 0; count < string.length; string++) {
if (string.charAt(count) == "B") {
result += 1;
return result;
}
}
};
You currently have:
function countBs(string) {
var result = 1;
var string = prompt("Please Enter a String");
for (count = 0; count < string.length; string++) {
if (string.charAt(count) == "B") {
result += 1;
return result;
}
}
}
which should be:
function countBs(string) {
var result = 0;
var string = prompt("Please Enter a String");
for (count = 0; count < string.length; count++) {
if (string.charAt(count) == "B") {
result += 1;
}
}
return result;
}
(notice the count++, the change from 0->1 for result, and the moved return)
I think you want this:
function countBs(string) {
var result = 0;
var string = string || prompt("Please Enter a String");
for (var count = 0; count < string.length; ++count)
if (string.charAt(count) == "B")
result += 1;
return result;
};
Make sure it's "var count" and not just "count" or you will pollute the global sapce.
There are other ways as well:
"BBBBBB".split('B').length-1
and
("BBBBBBB".match(/B/g)||"").length
or case insensitive
("BbBbBbB".match(/B/gi)||"").length
function countBs() { // no parameter
var string = prompt("Please Enter a String"); // provide string
return string.split('').reduce(function (x, letter) { // string became array and array can use build in method reduce
return letter === 'B' ? x + 1 : x; // test for B and return increment, otherwise old count
}, 0); // start with count 0
};
take the string and make a real array, and then iterate over all letters and count the Bs
You need to change string in the for loop to count
function countBs(string) {
var result = 1;
var string = prompt("Please Enter a String");
for (count = 0; count < string.length; count++) {
if (string.charAt(count) == "B") {
result += 1;
}
}
return result;
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.