I have the following js and receiving error at the foreach
loop:
function bitCount(n) {
var strBitCount = (n >>> 0).toString(2);
var answer = 0;
var c = '';
foreach(c in strBitCount)
{
if(Number(c) == 1)
{
answer++;
}
}
return answer;
}
I have the following js and receiving error at the foreach
loop:
function bitCount(n) {
var strBitCount = (n >>> 0).toString(2);
var answer = 0;
var c = '';
foreach(c in strBitCount)
{
if(Number(c) == 1)
{
answer++;
}
}
return answer;
}
Share
Improve this question
asked Mar 27, 2016 at 19:39
J.S.OrrisJ.S.Orris
4,82114 gold badges58 silver badges98 bronze badges
1
|
3 Answers
Reset to default 16JavaScript has no foreach
block as other languages.
What you can do is using Array.prototype.forEach
:
Array.from("hello").forEach(function(character) {
console.log(character);
});
Well, and in ES2015 and above, you can use for..of
for (let character of "hello") {
console.log(character);
}
You can use an ordinary for
loop and index into the string with []
:
for (var i = 0; i < strBitCount.length; ++i)
if (Number(strBitCount[i]) === 1)
answer++;
Note that you could also just add the digit to answer
:
for (var i = 0; i < strBitCount.length; ++i)
answer += Number(strBitCount[i]); // or +strBitCount[i]
You can filter
on those characters in the string that match your test and return the length of that array.
function bitCount(n) {
var strBitCount = (n >>> 0).toString(2);
var equalsOne = function (char) { return +char === 1; }
return [].filter.call(strBitCount, equalsOne).length;
}
DEMO
forEach
is an array method:arr.forEach(function (el) {...}
– Andy Commented Mar 27, 2016 at 19:40