How to use continue in a loop to change a value - javascript

I am trying to have a loop that gives me values from 1 to 30. However every number divisible by 10 I want to hard code the value to the corresponding word. Example would be value 10 = "Ten", 20 = "Twenty" and so on.
I tried to do this with 'continue', however my displayed results do not go pass "Ten".
for (i = 0; i <= 30; i++) {
if (i == 10) {
i = "Ten";
continue;
} if (i == 20) {
i = "Twenty";
continue;
}
console.log(i);
}
Results
Am I going on about it the right way? Could you please offer some hints so I can figure this out. Thank you,
I tried this initially. But didn't work.
for (i = 0; i <= 30; i++) {
if (i == 10) {
i = "Ten";
} if (i == 20) {
i = "Twenty";
}
console.log(i);
}

Just get rid of the continue statements. They cause the loop to immediately skip to the end and start another iteration. Thus, your console output statement is skipped. Also, you don't want to touch the loop variable, and it wouldn't hurt to have an else. Something like this:
var result;
for (i = 0; i <= 30; i++) {
if (i == 10) {
result = "Ten";
} else if (i == 20) {
result = "Twenty";
} else {
result = i;
}
console.log(result);
}
Or you could just log the desired output directly in each branch of the if/else chain:
for (i = 0; i <= 30; i++) {
if (i == 10) {
console.log("Ten");
} else if (i == 20) {
console.log("Twenty");
} else {
console.log(i);
}
}

I dont think you can change i and expect it to work as usual. hence as soon as you change the value to "TEN", the loop terminates..!!!!

When the counter i gets to ten, you are replacing it with a string, so when the control flow reaches the i++ part, your loop fails. What you should do is assign the value to be printed to another variable that is only used inside the body of the loop.

Related

Java Script - Give certain array elements different colour

I am trying to do something with JS but as per usual arrays prove to be the bane of my existence...
I have to loop through the numbers from 1 to 100 and print them in the HTML, every number that divides by 3 should show in the colour red while all other numbers should be black. I tried so many things and tried to find how to do it but could not figure it out. Could anyone, please, tell me what is the proper way to do it?
You can use the following code to get what you are looking for.
for (let i = 1; i < 101; i++) {
if(i % 3 == 0) {
console.log('THREE');
} else {
console.log(i)
}
}
If you need to write the values to a document, change the console.log to document.write
Put the THREE in some inline element and add css rule to change the color.
For printing the list the solution explained by Jack. (Did it differently because I could.)
const text = (new Array(100))
.fill('')
.map((_v, i) => (i % 3) === 0 ? `<b>THREE</b>` : i)
.join('<br/>');
document.write(`<p>${text}</p>`)
b {
color: red;
}
First, loop through the numbers 1 to 100:
for (var i = 1; i <= 100; i++) {
//Stuff will go here
}
Then, write the number i to HTML:
document.write(i);
Finally, add the if statement:
if (i % 3) {
document.write(i);
} else {
document.write("THREE");
}
Full code:
for (var i = 1; i <= 100; i++) {
if (i % 3) {
document.write(i + "<br>");
} else {
document.write("THREE<br>");
}
}
EDIT
Here's how you'd make THREE red:
for (var i = 1; i <= 100; i++) {
if (i % 3) {
document.write(i + "<br>");
} else {
document.write("<span style='color: red;'>THREE</span><br>");
}
}

How to implement .map() using for()?

I have these array and variable:
var arr = [['one','blue'], ['two','red'], ['three','green']]
var variable = 'thre';
Also I have this code:
arr.map(function(x){
if(x[0].indexOf(variable) >= 0)
{
alert('Number is found');
}
});
As you know, map works as a loop, and in the array above, there is three items and then map executes its statement 3 times. So that alert will be run.
Now I'm trying to limit the mapping, I mean I want to execute a statement 2 times. So I user for() like this:
for ( var c = 0; c < 2; c++ ) {
if ( arr[c][0].indexOf(variable) >= 0 )
{
alert('number is found');
}
}
But ^ doesn't work, It gives me this error:
Uncaught TypeError: Cannot read property '0' of undefined {in line 2}
How can I fix it?
EDIT: Here is my code in reality:
ZippedArray.map(function(x){
if(x[0].indexOf(name) >= 0)
{
MatchesNames.push(x[0]);
MatchesIds.push(x[1]);
}
});
I want this output:
MatchesNames = MatchesNames.slice(0,2);
MatchesIds = MatchesIds.slice(0,2);
How to limit .map() ? I want something like break; after 2 times.
Based on your comments, it seems you want to loop until you've found two matches in the if condition.
In that case, you can use .some(), which will halt the loop as soon as you return true (or any truthy value).
ZippedArray.some(function(x){
if(x[0].indexOf(name) >= 0)
{
MatchesNames.push(x[0]);
MatchesIds.push(x[1]);
}
return MatchesNames.length == 2; // Breaks when this returns `true`
});
This example assumes that MatchesNames was empty before you called .some().
If there could be other items in the array, and you just want to push two more in at the most, then you could keep a count.
var found = 0;
ZippedArray.some(function(x){
if(x[0].indexOf(name) >= 0)
{
MatchesNames.push(x[0]);
MatchesIds.push(x[1]);
found++;
}
return found == 2;
});
If you want to use a traditional for loop, then do this:
var found = 0;
for (var i = 0; i < ZippedArray.length; i++) {
var x = ZippedArray[i];
if(x[0].indexOf(name) >= 0)
{
MatchesNames.push(x[0]);
MatchesIds.push(x[1]);
found++;
}
if (found == 2) {
break;
}
}
The code you posted does not throw an error.
But when you're limiting the loop count of iterating an array, you should add a range check for the index:
for (var c = 0; c < 2 && c < arr.length; c++) {
// or alternatively
for (var c = 0, l = Math.min(2, arr.length); c < l; c++) {

Returning factorials in JavaScript

I'm trying to create a script that returns the factorial of the input number as part of a challenge. When I try to run it, it returns the proper factorial, but apparently I did it wrong somehow.
It looks like this:
function FirstFactorial(num) {
if (num > 1) {
var x = num;
for (var i = 1; i < x; i++) {
num = num * i;
}
} else if (num === 1) {
return 1;
} else {
console.log("That's not a number!");
}
return num;
}
Then I tried doing it like this, but it still doesn't work!
function FirstFactorial(num) {
if (num < 0) {
num = 0;
console.log("You have to input a number!");
}
if (num === 0) {
return 1;
}
return num * FirstFactorial(num - 1);
}
The most likely reason is that they expected and intended you to use recursion (a function that calls itself).
If you think about factorials, each builds on the result of the previous one, which is the classic case for using recursion.
(Note that I'm specifically not posting code doing this with recursion, because presumably the point here is for you to work out how to do it.)

Fizz Buzz return value javascript

I'm having an assignment where I have to do the FizzBuzz game in Javascript.
The problem is my loop stops after the first iteration and only return the first value (4). I may be blind to my code but I can't find where the error(s) is.
If you could please push me in the right direction I'd be happy. Thanks in advance. Regards, Thomas.
function fizzBuzz(start, stop) {
for(var i = start; i <= stop; i++) {
if (i % 3 == 0) {
return "fizz";
}else if( i % 5 == 0) {
return "buzz";
}else if(i % 15 == 0) {
return "fizz buzz";
}else {
return i;
}
}
}
ANSWER = (fizzBuzz(4, 22));
New code:
function fizzBuzz(start, stop) {
for(var i = start; i <= stop; i++) {
if (i % 3 == 0 && i % 5 == 0) {
document.write ("Fizz Buzz");
}else if(i % 3 == 0) {
document.write ("Fizz");
}else if(i % 5 == 0) {
document.write ("Buzz");
}else {
document.write(i);
}
}
}
ANSWER = (fizzBuzz(4, 22));
It returns: Answer = undefined
When your code encounters the return statement, the value given is returned from the whole function. This stops the for loop from iterating any further.
These are the questions you'll need to ask yourself:
What do you want to the fizzBuzz function to do? Should it print the text somewhere, or should it return a value?
If fizzBuzz should return a value, what would you expect that it returns? One line of text? Multiple lines of text all at once?
Whatever branch is taken within your for loop, there is always a return which exits the funtion with a return value. So, when you start with 4, the program enters the else branch and returns 4.
What you want is to print the value instead of returning from the function.
Also, I can see a logical error in the code. Assume i is 15, which is divisible by 3 and 5. Your program will go into the i % 3 branch and return "fizz" instead of "fizz buzz". You may want to change your if statements and/or work with string concatenation.
Hope I could help. ;)
One of the best solution in javascript to the fizzbuzz problem
const fizzbuzz = (start, stop) => {
const arr = [];
let str;
for(let i=start; i<=stop; i++) {
str = "";
if(i%3===0) {
str = "fizz";
}
if(i%5===0) {
str += "buzz";
}
arr.push(str||i);
}
return arr;
}
console.log(fizzbuzz(0, 105));

How to break nested loops in JavaScript? [duplicate]

This question already has answers here:
What's the best way to break from nested loops in JavaScript? [closed]
(18 answers)
Closed 3 years ago.
I tried this:
for(i = 0; i < 5; i++){
for(j = i + 1; j < 5; j++){
break(2);
}
alert(1);
}
only to get:
SyntaxError: missing ; before statement
So, how would I break a nested loop in JavaScript?
You should be able to break to a label, like so:
function foo () {
dance:
for (var k = 0; k < 4; k++) {
for (var m = 0; m < 4; m++) {
if (m == 2) {
break dance;
}
}
}
}
You need to name your outer loop and break that loop, rather than your inner loop - like this.
outer_loop:
for(i=0;i<5;i++) {
for(j=i+1;j<5;j++) {
break outer_loop;
}
alert(1);
}
There are at least five different ways to break out of two or more loops:
1) Set parent(s) loop to the end
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
{
i = 5;
break;
}
}
}
2) Use label
fast:
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
break fast;
}
}
3) Use variable
var exit_loops = false;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
{
exit_loops = true;
break;
}
}
if (exit_loops)
break;
}
4) Use self executing function
(function()
{
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
return;
}
}
})();
5) Use regular function
function nested_loops()
{
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
return;
}
}
}
nested_loops();
See Aaron's. Otherwise:
j=5;i=5 instead of break.
loop1:
for (var i in set1) {
loop2:
for (var j in set2) {
loop3:
for (var k in set3) {
break loop2; // breaks out of loop3 and loop2
}
}
}
code copied from Best way to break from nested loops in Javascript?
Please search before posting a question. The link was the FIRST related question I saw on the left side of this page!
Unfortunately you'll have to set a flag or use labels (think old school goto statements)
var breakout = false;
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
breakout = true;
break;
}
if (breakout) break;
alert(1)
};
The label approach looks like:
end_loops:
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
break end_loops;
}
alert(1)
};
edit: label incorrectly placed.
also see:
http://www.devguru.com/Technologies/ecmascript/quickref/break.html
http://www.daaq.net/old/javascript/index.php?page=js+exiting+loops&parent=js+statements
In my opinion, it's important to keep your construct vocabulary to a minimum. If I can do away with breaks and continues easily, I do so.
function foo ()
{
var found = false;
for(var k = 0; (k < 4 && !found); k++){
for(var m = 0; (m < 4 && !found); m++){
if( m === 2){
found = true;
}
}
}
return found;
}
Be warned, after the loop, m and k are one larger that you might think. This is because m++ and k++ are executed before their loop conditions. However, it's still better than 'dirty' breaks.
EDIT: long comment #Dennis...
I wasn't being 100% serious about being 'dirty', but I still think that 'break' contravenes my own conception of clean code. The thought of having multi-level breaks actually makes me feel like taking a shower.
I find justifying what I mean about a feeling about code because I have coded all life. The best why I can think of it is is a combination of manners and grammar. Breaks just aren't polite. Multi level breaks are just plain rude.
When looking at a for statement, a reader knows exactly where to look. Everything you need to know about the rules of engagement are in the contract, in between the parenthesis. As a reader, breaks insult me, it feels like I've been cheated upon.
Clarity is much more respectful than cheating.
Use function for multilevel loops - this is good way:
function find_dup () {
for (;;) {
for(;;) {
if (done) return;
}
}
}
Wrap in a self executing function and return
(function(){
for(i=0;i<5;i++){
for (j=0;j<3;j++){
//console.log(i+' '+j);
if (j == 2) return;
}
}
})()
You return to "break" you nested for loop.
function foo ()
{
//dance:
for(var k = 0; k < 4; k++){
for(var m = 0; m < 4; m++){
if(m == 2){
//break dance;
return;
}
}
}
}
foo();
break doesn't take parameters. There are two workarounds:
Wrap them in a function and call return
Set a flag in the inner loop and break again right after the loop if the flag is set.
Break 1st loop:
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
//do something
break;
}
alert(1);
};
Break both loops:
for(i=0;i<5;i++)
{
var breakagain = false;
for(j=i+1;j<5;j++)
{
//do something
breakagain = true;
break;
}
alert(1);
if(breakagain)
break;
};
You can break nested for loops with the word 'break', it works without any labels.
In your case you need to have a condition which is sufficient to break a loop.
Here's an example:
var arr = [[1,3], [5,6], [9,10]];
for (var a = 0; a<arr.length; a++ ){
for (var i=0; i<arr[a].length; i++) {
console.log('I am a nested loop and i = ' + i);
if (i==0) { break; }
}
console.log('first loop continues');
}
It logs the following:
> I am a nested loop and i = 0
> first loop continues
> I am a nested loop and i = 0
> first loop continues
> I am a nested loop and i = 0
> first loop continues
The return; statement does not work in this case.
Working pen
function myFunction(){
for(var i = 0;i < n;i++){
for(var m = 0;m < n;m++){
if(/*break condition*/){
goto out;
}
}
}
out:
//your out of the loop;
}

Categories

Resources