I need to show in console the numbers from 1 to 20 without an array..that s what i did:
function oneToTwenty() {
for (i = 1; i <= 20; i++) {
print i;
}
}
console.log(i);
what is wrong?
The console.log(i); should be inside the for loop:
for (i = 1; i <= 20; i++) {
console.log(i);
}
there's no such thing as "print". use console.log instead of print.
You also have an extra closing "}", which doesn't make sense.
for (i = 1; i <= 20; i++) {
console.log(i);
}
You need to put your console.log inside the loop. Otherwise, you firstly do the looping and then try to log the non-existent i.
Also, note that you have to declare i, if you have not done it, using var or let.
for (let i = 1; i <= 20; i++) {
console.log(i);
}
Related
So, in this code I have a string of 0's and 1's and the length of the string is 32, which will be split in 6 equal parts but the last part will have the length of 2 so I will add (4) 0's after that which will make its length 6. So I wrote a function that will add the remaining 0's which is padding(num).
And that function will be invoked in side the slicing(str) function.
But the code breaks when I try to do execute.
Any help?
Thanks.
// This code works.
function padding0s(num) {
let s = "";
for (i = 0; i < 6 - num; i++) {
s += "0";
}
return s;
}
function slicing(str) {
let k = 6;
let res = [];
let temp1 = 0;
let f = padding0s(2);
for (i = 0; i < str.length; ) {
res.push(str.slice(i, k));
i += 6;
k += 6;
if (res[temp1].length !== 6) {
res[temp1] += f;
}
temp1++;
}
console.log(res);
}
slicing("01000011010011110100010001000101");
// But this does not..
function padding0s(num) {
let s = "";
for (i = 0; i < 6 - num; i++) {
s += "0";
}
return s;
}
function slicing(str) {
let k = 6;
let res = [];
let temp1 = 0;
for (i = 0; i < str.length; ) {
res.push(str.slice(i, k));
i += 6;
k += 6;
if (res[temp1].length !== 6) {
let f = padding0s(res[temp1].length);
res[temp1] += f;
}
temp1++;
}
console.log(res);
}
slicing("01000011010011110100010001000101");
Always define variables before using them
Not doing so can result in undefined behaviour, which is exactly what is happening in your second case. Here is how:
for (i = 0; i < str.length; ) {...}
// ^ Assignment to undefined variable i
In the above for-loop, by using i before you define it, you are declaring it as a global variable. But so far, so good, as it doesn't matter, if not for this second problem. The real problem is the call to padding0s() in your loop. Let's look at padding0s:
function padding0s(num) {
...
for (i = 0; i < 6 - num; i++) {
s += "0";
}
}
This is another loop using i without defining it. But since i was already defined as a global variable in the parent loop, this loop will be setting its value. So in short, the value of i is always equal to 6 - num in the parent loop. Since your exit condition is i < str.length, with a string of length 32 the loop will run forever.
You can get around this in many ways, one of which you've already posted. The other way would be to use let i or var i instead of i in the parent loop. Even better is to write something like this (but beware that padEnd may not work on old browsers):
function slicing(str) {
return str.match(/.{1,6}/g).map((item) => {
return item.padEnd(6, "0");
});
}
console.log(slicing("01000011010011110100010001000101"));
I am trying to debug my code.
When I add console.log('aaa'); it shows ok in the test output
When I add console.log statements within a for loop however
console.log('aaa');
for(let i = 0; i++; i < 10) {
console.log(i);
}
I get the 'aaa' as output but I do not get the numbers in the loop.
The for loop should have the check before the increment
for(let i = 0; i < 10; i++)
^ ^
switch these
I am currently learning JavaScript, and right now I am on a topic discussing the differences between let and var.
Can someone explain why this code prints 3 and not 2? How does i even reach the value of 3 when the loop should stop executing once i becomes 2?
var i;
function printNumTwo() {
return i;
}
for (i = 0; i < 3; i++) {
if(i === 2) {
printNumTwo();
}
}
print(printNumTwo()); // prints 3
You are not printing anything while i is 2, only after the loop is when you call print. The Loop stops when i becomes 3.
To have it print 2, you have to change the printNumTwo() function like so:
var i;
function printNumTwo() {
print(i);
}
for (i = 0; i < 3; i++) {
if(i === 2) {
printNumTwo();
}
}
it because you have this line
for (i = 0; i < 3; i++) {
which increment value of i, and i is global variable and when you call you printNumTwo i value reached to 3 because of loop increment i value
When you print(printNumTwo()) i is 3. Calling printNumTwo() in the if statement does nothing but returning i which is not used by anything.
So basically the for statement runs and finishes making i=3 and then i is used by your print method.
You have to change start loop with let keyword because var is a global variable and let is block scope variable. that's why getting the different value.
You can try this
var i;
function printNumTwo() {
return i;
}
for (let j = 0; j < 3; j++) {
i = j;
if(i === 2) {
printNumTwo();
}
}
cosole.log(printNumTwo());
Try to use break statement it "jumps out" of a loop and continues executing the code after the loop if the specified condition is true.
var i;
function printNumTwo() {
return i;
}
for (i = 0; i < 3; i++) {
if (i === 2) {
break;
printNumTwo();
}
}
document.write(printNumTwo()); // prints 2
Why does the else and if statement print? Checking if arrays have matching
elements on line 5 which they do...so just my if statement should print.
However my alert condition prints with the if condition.I've tried rearranging code,still no luck.
var array1 = [1, 89, 3, 4, 5];
var array2 = [1, 2, 7, 10, 89];
for (var i = 0; i < 6; i++) {
for (var j = 0; j < 6; j++) {
if (array1[i] == array2[j]) {
document.getElementById("demo").innerHTML =
"Hello World" //Should just print this since elements match
break;
} else {
alert("Error");
break;
}
}
}
If you want to stop the outer loop when you find a match in the inner loop, you need to give a label parameter to break.
outer:
for (var i = 0; i < 6; i++) {
for (var j = 0; j < 6; j++) {
if (array1[i] == array2[j]) {
document.getElementById("demo").innerHTML =
"Hello World" //Should just print this since elements match
break outer;
} else {
alert("Error");
break;
}
}
}
You still may get some alerts before Hello World is displayed. Your code alerts for every non-matching pair of elements until it finds a match. So unless the matching elements are first in both arrays, you'll get a bunch of alerts before it displays Hello world.
Also, since you have break in both the if and else blocks, you'll never get past the first iteration of the j loop.
If you just want a single alert that indicates that no matching elements were found, you need to move it out of the loop.
var match_found = false;
outer:
for (var i = 0; i < 6; i++) {
for (var j = 0; j < 6; j++) {
if (array1[i] == array2[j]) {
document.getElementById("demo").innerHTML =
"Hello World" //Should just print this since elements match
match_found = true;
break outer;
}
}
}
if (!match_found) {
alert("Error");
}
a for loop will repeat very quickly, which is why you can not see the them doing it at diffrent times;
your code does not output at the same time, it is just to fast.
if you are looking into delay, take a look at setInterval.
Just skip the else part. You don't really need that. Unless you wish to do something else if the condition is not true, omit the else statement.
When you call break it only terminates the inner loop. The outer loop will continue to iterate, your conditions will be checked again, and then the else statements run instead.
An alternative way to do this would be:
(function() {
for (var i = 0; i < 6; i++) {
for (var j = 0; j < 6; j++) {
if (array1[i] == array2[j]) {
document.getElementById("demo").innerHTML =
"Hello World" //Should just print this since elements match
return;
} else {
alert("Error");
return;
}
}
}
})();
Wrapping the code in a self executing function allows you to replace break with return to exit the entire function.
I want to do a for loop that is looping 50 times but I need the code block inside the loop to run just on multiples of nine(9,18,27,36..)
How can I do it?
for(var i=0; i<450; i+=9) {
...
}
Alternatively, for better readability:
for(var nines = 0, loop_counter=0; loop_counter<50; loop_counter += 1, nines = loop_counter*9) {
...
}
Something like this:
for(var i = 0; i < 50; i++) {
if (i % 9 == 0) {
//code block here
}
}
for(var i = 0; i < 50; i++) {
if (i % 9 == 0) {
console.log(i);
}
}
fiddle
for(var i = 0; i < 450; i += 9) {
console.log(i);
}
fiddle
for (var i = 1; i <= 50; ++i) {
(function(multipleOfNine) {
// Do something with multipleOfNine
}(i * 9));
}
I interpreted your question to mean you want to loop over the first 50 multiples of nine. If what you meant was you want just the multiples of nine under 50, then use EnterSB's answer.
Record which iteration of the loop you are in (simplest way is to initialize a variable outside the loop to 0 and then increment it every time you go through the loop) and then use Modulo to check if it's divisible by 9. e.g. x=i%9. If x is 0 then i's a multiple of 9.