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>");
}
}
Related
[ETA] for better clarification:
I'm currently learning to code a HTML canvas game (items catching and dodging) using Javascript for a class project and I'm having problem with getting the objects falling down from top of the canvas.
The problem I'm having currently is occasionally (one might need to reload the game several times to notice this phenomenon) an object 'jumps' out of a random point inside the canvas where it should be thrown back up to the negative y coordinate area (aka. out of sight) and fall down again from there after collision detection.
So for example, when a giftbox is caught or disappears off the bottom edge, it should be thrown back up to the top of the canvas. However, sometimes it pops out of a random point in the middle, or near the bottom edge of the canvas instead, which is not at all what I intended.
I figure there must be a logical error with the code I write, but I have been trying several fixes and looking up answers for the past few days without any success.
I guess the problem must lie in the part of the code where I do collision detection:
function fallAgain() {
for (i = 0; i < 3; i++) {
let r = Math.floor(Math.random() * objectArray.length);
if (objectArray[i].y > canvas.height) {
[objectArray[i], objectArray[r]] = [objectArray[r], objectArray[i]];
objectArray[r].y = randomY();
objectArray[r].x = randomX();
// this loop is to check if two randomly generated items overlap
for (let idx = 1; idx < 3; idx++) {
if (Math.abs(objectArray[idx].x - objectArray[idx-1].x) <= 10
&& Math.abs(objectArray[idx].y - objectArray[idx-1].y) <=10) {
objectArray[idx].y += 30;
objectArray[idx].x += 20;
}
}
if (objectArray[r].status == 1
|| objectArray[r].status == 3
|| objectArray[r].status == 4) {
lives--;
}
}
}
}
function hitOrMissed() {
for (i = 0; i < 3; i++) {
let r = Math.floor(Math.random() * objectArray.length);
if (objectArray[i].x + objectArray[i].w > kid.x + 3
&& objectArray[i].x + 3 < kid.x + kid.w
&& objectArray[i].y + objectArray[i].h > kid.y
&& objectArray[i].y < kid.y + kid.h - 3) {
[objectArray[i], objectArray[r]] = [objectArray[r], objectArray[i]];
objectArray[r].y = randomY();
objectArray[r].x = randomX();
for (let idx = 1; idx < 3; idx++) {
if (Math.abs(objectArray[idx].x - objectArray[idx-1].x) <= 10
&& Math.abs(objectArray[idx].y - objectArray[idx-1].y) <=10) {
objectArray[idx].y += 30;
objectArray[idx].x += 20;
}
}
if (objectArray[r].status == 1) {
score++;
} else if (objectArray[r].status == 0) {
lives--;
} else if (objectArray[r].status == 4) {
if (lives < 2) {
lives++;
} else {
lives += 0;
score += 2;
}
} else if (objectArray[r].status == 3) {
score += 5;
}
}
}
}
So far I've tried merging the fallAgain and hitOrMissed functions, but the problem persists
And here's my Codepen with the full code:
Codepen demo
If someone could please help me identify where I've made it wrong and a pointer or guideline as to what I should do to fix the problem I'd really appreciate it. I'm not sure if this piece of information is of any help, but I'm just a beginner at Javascript with no prior coding experience and I've only learned the basics (I haven't touched constructor and Object-oriented Programming yet).
Thank you so much in advance for your help!
Can you pleas etake a look at this demo and let me know why I am not able to create multiple increment in a loop
var i;
for (i = 0; i < 100;) {
console.log(i);
if (i < 50) {
i++;
}
if (i > 50) {
i += 2;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The problem with your code is that when i == 50, it doesn't get incremented, so it goes into an infinite loop. You need to change one of the conditions to include 50, e.g.
for (var i = 0; i < 100;) {
console.log(i);
if (i < 50) {
i++;
}
else if (i >= 50) {
i += 2;
}
}
Note that stack snippets crop the console output, so it appears to be starting at 25 when in fact it will start at 0.
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.
I have an assignment for school that I seem to be stuck on.
Write a script that prints the prime numbers between 1 and 999 in a table that consists >of 10 columns. Use document.write() statements to create the table elements and a >counter variable to create the table so that it consists of 10 columns. The counter >variable should start with an initial value of 0 and be incremented by one each time your >code identifies a prime number and prints it in a table cell. Once the counter variable >reaches a value of 10 (meaning that 10 cells have been added to the current row), print >to start a new row and reset the variable to 0.
I cannot figure out where my error or errors are with the table row and counter. Also, I might have placed the document.write() methods in the wrong places. Currently, the table only displays vertically.
Here is what I have:
<script>
function primeNumbers(num) {
document.write('<table>');
if (num < 2)
return false;
for (var i = 2; i < num; i++) {
if (num % i == 0)
return false;
}
return true;
}
document.write('<tr>');
var counter = 0;
for (var i = 0; i < 999; i++) {
if (primeNumbers(i)) {
if (counter % 10 == 0) {
document.write('</tr><tr>');
counter = 0;
}
counter++;
document.write('<td>' + i + '</td>');
}
}
document.write('</table>');
</script>
Please, push me in the right direction and don't give me the answer. I want to see if I can figure this out.
Thanks!
There were some errors in your code:
The <table> opener was inside the function, so actually it was opening 1000 times.
The counter is reset, so you don't need to use modulus (%), just compare to 10.
A </tr> was missing in the end
Your function primeNumbers is misnamed, the best would be call isPrime
Here's the code:
function isPrime(num) {
if (num < 2) return false;
for (var i = 2; i < num; i++) {
if (num % i == 0) return false;
}
return true;
}
document.write("<table><tr>");
var counter = 0;
for (var i = 0; i < 999; i++) {
if (isPrime(i)) {
if (counter == 10) {
document.write('</tr><tr>');
counter = 0;
}
counter++;
document.write('<td>' + i + '</td>');
}
}
document.write('</tr></table>');
Here's the fiddle working (I can't use document.write here, but you get the idea) http://jsfiddle.net/bortao/D2bzk/
Try this: http://jsfiddle.net/ezn7f/
<script>
function primeNumbers(num) {
if (num < 2)
return false;
for (var i = 2; i < num; i++) {
if (num % i == 0)
return false;
}
return true;
}
document.write('<table><tr>');
var counter = 0;
for (var i = 0; i < 999; i++) {
if (primeNumbers(i)) {
if (counter % 10 == 0) {
document.write('</tr><tr>');
counter = 0;
}
counter++;
document.write('<td>' + i + '</td>');
}
}
document.write('</table>');
</script>
I wonder if this is what you are looking for though. I didn't change much in your code.
I am trying to achieve a check with the if...else statement that only squares the odd numbers between 100 and 150, otherwise the number is just printed.
How can I revise my if statement to achieve this please? An educated guess is that an operator or combination of operators are used.
for (i=100; i<=150; i++)
{
if (i === 0)
{
console.log(i * i);
}
else
{
console.log(i);
}
}
The operator you are looking for is %:
for(i = 100; i <= 150; i++) {
if(i % 2 === 1) { // It's odd
console.log(i * i);
} else {
console.log(i);
}
}
a % b is basically the remainder obtained when a is divided by b. It's called the modulus operator.
Two words: Modulus Division
A nice reference
if ( i % 2 === 0) {
console.log(i)
} else {
console.log(i * i)
}
Squares odd numbers.