0

How can I stop loop when the first time if condition is true?

<p id="numb"></p>

And here is my code javascript, Where i did mistake? i want that when the condition is true the loop stops and don't check other variants?

function round (number) {
    var str = number.replace(/[, .]/g, "");
    var numb = parseInt(str);
    var point = {
        "T": Math.pow(10, 12),
        "B": Math.pow(10, 9),
        "M": Math.pow(10, 6),
        "K": Math.pow(10, 3)
    };

    Object.keys(point).forEach(function (key) {
        var pNumb = point[key];
       // console.log(pNumb);
      //  console.log(key);
        if (pNumb < numb) {
            var letter  = key;
            console.log(letter);
            var z = numb / pNumb;
            if (numb % pNumb !== 0) {
                document.getElementById("numb").innerHTML = z.toFixed(1) + letter;
            } else {
                document.getElementById("numb").innerHTML = z + letter;
            }
            return false;
        }

    });
}
    round("665,421,000")
Alexandra
  • 11
  • 2

2 Answers2

1

Returning false will not stop a forEach loop early. The only way to stop such a loop early is to throw an exception (which you need to catch outside the loop).

I normally recommend using a for...of loop instead of forEach, if you are using a new enough version of Javascript. But in this case, since you're calling forEach on the result of calling Object.keys() on the object (instead of the object itself), you can just use a for...in loop, which has been in Javascript forever.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175
  • Ok i understand thanks, but i fixed it with for in loop is it wrong way? – Alexandra Feb 06 '18 at 20:08
  • Since you were iterating over the `keys` of the object, `for`...`in` is actually correct. If you were just calling `forEach` on the object itself, the replacement would be `for`...`of`. – Mark Reed Feb 06 '18 at 20:46
0

Besides forEach not returning a value if you return from it, your code is wrong, because you're assuming object keys maintain their order, you should write something like this instead:

function round (number) {
    const str = number.replace(/[, .]/g, "");
    const numb = parseInt(str);
    const point = [
        ["T", Math.pow(10, 12)],
        ["G", Math.pow(10, 9)],
        ["M", Math.pow(10, 6)],
        ["K", Math.pow(10, 3)]
    ];

    for (const [key, pNumb] of point) {
        if (pNumb < numb) {
            const letter  = key;
            const z = numb / pNumb;
            if (numb % pNumb !== 0) {
                return z.toFixed(1) + letter;
            } else {
                return z + letter;
            }
        }
    }
}

You also have a typo, instead of "G", you have "B".

Francisco
  • 10,918
  • 6
  • 34
  • 45