5

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;
}
1
  • 2
    forEach is an array method: arr.forEach(function (el) {...} Commented Mar 27, 2016 at 19:40

3 Answers 3

16

JavaScript 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);
}

Sign up to request clarification or add additional context in comments.

2 Comments

I accidentally hit the downvote I think....mad it an upvote...thanks for your answer.
@JeffOrris No problem. I've checked you found more useful other answer. BTW I still think that now you know that foreach doesn't syntactically exist in JavaScript.
2

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]

Comments

1

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

1 Comment

Very nice sir! and elegant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.