最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I loop through chars in a string in javascript? - Stack Overflow

programmeradmin1浏览0评论

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

3 Answers 3

Reset to default 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);
}

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

发布评论

评论列表(0)

  1. 暂无评论