I'm currently studying javascript and I don't understand the result based on a specific condition. Thanks for you patience with newbies like myself ;)
In the following case, I don't understand why the last line "blue" is displayed since the condition is "show only when counter > 0".
var table = ['blue','yellow','orange','red'];
for (var counter = table.length ; counter > 0 ; counter--)
{
document.write(table[counter-1] + "<br>")
}
Another way to see the result would be :
var table = ['blue','yellow','orange','red'];
document.write(table[table.length-1] + '<br>'); // result: table[3] "red"
document.write(table[table.length-2] + '<br>'); // result: table[2] "orange"
document.write(table[table.length-3] + '<br>'); // result: table[1] "yellow"
document.write(table[table.length-4] + '<br>'); // result: table[0] "blue" = should not be displayed if we have the condition 'counter > 0'
Thanks for your help!
Because you are using -
var table = ['blue','yellow','orange','red'];
for (var counter = table.length ; counter > 0 ; counter--)
{
document.write(table[counter-1] + "<br>") //when table has 4 item, counter = 1, counter > 0, table[counter - 1] = table[0]
}
In other words, your code perfectly prints all. If you wish to skip the last one do this -
var table = ['blue','yellow','orange','red'];
for (var counter = table.length - 1; counter > 0 ; counter--)
{
document.write(table[counter] + "<br>")
}
In the below line:
document.write(table[counter-1] + "<br>"), you are decrementing the counter by 1. It will not validate the condition here.
Use this counter - 1 > 0
It is because inside your loop, you are using table[counter-1].
Counter never reaches 0 but you take away 1 from it, which makes it access the zero'th element of table
In JavaScript arrays are initiate in index 0. In your conditional you do loop from length array until 1 "counter >0" but when you print the array item you get counter-1, if counter is equal 1 you will get array index 0.
Related
Why when I use the following codes in JS it works properly ?:
let counter = 5;
while (counter < 10) {
console.log(counter);
counter ++;
}
But when I try the following codes it doesn't?
let counter = 5;
while (counter < 10) {
console.log(counter);
counter + 1;
}
You're missing an assignment there.
counter++ directly increases the counter itself by one.
counter + 1 just returns the value of counter plus one.
Solutions might be:
counter += 1;
counter = counter + 1;
This happens because on the second example, you are summing 1 to counter value, but it's not using this sum to nothing.
Let me exemplify:
let c = 0;
console.log(c + 1); // outputs 1
console.log(c); outputs 0, since in the last statement you didn't changed the original value, just used it.
console.log(c++); // will output c then increment c. So it prints the old value: 0
console log(c); will output 1 (result of previous increment)
console.log(++c); // will increment c and then output it new value: 2
Keep in mind that
c++;
Is the same that:
c = c + 1
The increment operator will increment a value and return a value that differs depending on whether it is used in a prefix or postfix position.
In postfix position it returns the original value:
let x = 0
console.log(x++) // 0 (!!)
console.log(x) // 1
In prefix position it returns the new value:
let x = 0
console.log(++x) // 1
console.log(x) // 1
You can type it out long hand if you want, using the addition and assignment operators separately:
let x = 0
console.log(x = x + 1) // 1
console.log(x) // 1
There is another operator too: the addition assignment operator:
let x = 0
console.log(x += 1) // 1
console.log(x) // 1
I'm supposed to create a function that will continue to double the first argument until it is greater than or equal to the 2nd argument. Every time it doubles, I add 20 to a counter.
However, for whatever reason, it doesn't seem to be adding 20 to the counter as it always returns 0 and does not print the console.log I included for each loop, which makes me think it's not running the loop.
Why isn't it running the loop and what am I doing wrong?
function bacteriaTime(currentNum, targetNum) {
let counter = 0
for (let i = currentNum; i >= targetNum; i *= 2) {
counter += 20;
console.log('bacteria count is ' + i + ' and ' + counter + ' have passed.')
}
return counter;
console.log(counter);
}
You might wanna check if your condition wasn't already met, and therefore, the code has returned. Also your condition is backwards. It should be: for (let i = currentNum; i <= targetNum; i *= 2) {
Seems like you've mixed up your comparison. In your for loop you had i >= targetNum which with your inputs would almost always be false. Simply switch the operator to <= as below and you should be good. This will mean i is less than targetNum.
function bacteriaTime (currentNum,targetNum){
let counter = 0
for (let i = currentNum; i <= targetNum; i *= 2){
counter += 20;
console.log ('bacteria count is ' + i + ' and ' + counter+ ' have passed.')
}
console.log(counter);
return counter;
}
Hope that works. It was probably just a simple mix up.
I have made array and all but i only need function that clears every second item from list and doing that job until there is only 1 item left for example i need something to do in array from 1-10 including 1 and 10 the result need to be 5?
Any sugestions it is similar like this but only need it for javascript not python
How to delete elements of a circular list until there is only one element left using python?
I am using this inside html body tag
var num = prompt("type num");
var array = [];
for (i = 1; i <= num; i++) {
array.push(i);
}
document.write(array + "<br>");
I tried this so far but this does not finish jobs great
while (i--) {
(i + 1) % 2 === 0 && array.splice(i, 1)
}
It does only first time deleting and leave array 1 3 5 7 9 i need it to be only 5 in this case because prompt is 10 in my case
The circular part makes it pretty tricky. Your loop condition should be on array length > 1, and within the loop you have to manually mess with the counter once it exceeds the length of the array - 2. If it's equal to arr.length, you want to skip the first element of the array the next time around, otherwise begin with the first element. Sorry I'm not explaining it better, here is the code.
var arr = [1,2,3,4,5,6,7,8,9,10];
var i = 1;
while (arr.length > 1) {
console.log("removing " + arr[i]);
arr.splice(i, 1);
var left = arr.length - i;
if (left == 0)
i = 1;
else if (left == 1)
i = 0;
else
i++;
}
console.log("result " + arr[0]);
Edit - This is almost exactly The Josephus Problem or see the episode from Numberphile on Youtube
There is a short recursive way to solve it. The parameter n is the largest number (similar to an array of n numbers from 1 to n), and k being the number of positions to skip at a time, (every other being 2).
var josephus = (n, k) => {
if (n == 1) return 1;
return (josephus(n - 1, k) + k-1) % n + 1;
};
console.log(josephus(10, 2));
while(array.length > 1) {
array = array.filter((_, index) => index % 2 === 0);
}
Basically, get rid of every second index as long as the length is greater than 1. The callback for filter allows value as the first parameter and index as the second, per MDN.
My code speaks for me, I want to wrap array index with another array dynamically (with a loop).
The following code does not work. Please, help me to convert this "x" string to JavaScript code or to find the right way to get the result.
var x = parentTasks[j];
while(x){
x = parentTasks + '[' + numbers + '[' + x + ']]';
}
Later "x" will become undefined, so then loop should stop.
What I expect:
Example when loop is iterated for 1st time:
parentTasks[numbers[parentTasks[j]]]
Example when loop is iterated for 2nd time:
parentTasks[numbers[parentTasks[numbers[parentTasks[j]]]]]
I did it by my self. Here is a solution:
var x = parentTasks[j];
var z = 0
while ( z++ < 2 ) {
x = 'parentTasks[numbers[' + x + ']]';
console.log(eval(x));
}
I am new to JavaScript and i am going through a task where i have to randomly disperse an input value between 12 loads. The other side is that each element of the array cannot differ from the next by more than one.
so for example if i have an amount of 30 i need to distribute this amount between 12 camels. I have so far written the code below, but i am using TextPad as requested i am not sure how to print out the result on the same line.
var amount = 30;
var camels = [0,0,0,0,0,0,0,0,0,0,0,0]
var div = amount/12;
var mod = amount%12;
var x = mod / 12;
for(i=0;i<camels.length;i++){
WScript.echo(camels[i] + "|" + Math.floor(div) + "|" + mod + "|" + x)
}
please comment if you need anymore info , Thanks
Here's my take on it. Note that for the requirement that states that the array values cannot differ from the next one by more than one, I consider the array to be looping, i.e. the value after the last value is the first value again.
var amount = 30;
var camels = [0,0,0,0,0,0,0,0,0,0,0,0];
while (amount > 0) {
var index = Math.floor(Math.random() * camels.length);
var previous = (camels.length + index - 1) % camels.length;
var next = (index + 1) % camels.length;
if (Math.abs(camels[index] + 1 - camels[previous]) <= 1
&& Math.abs(camels[index] + 1 - camels[next]) <= 1) {
camels[index]++;
amount--;
}
}
Update
As requested by the OP, here's an annotated version:
// the amount that needs to be distributed among the camels
var amount = 30;
// the actual values for all 12 camels, initially all zero
var camels = [0,0,0,0,0,0,0,0,0,0,0,0];
// as long as we have something to distribute
while (amount > 0) {
// get a random current index in the array, i.e. a value between 0 and 11
var index = Math.floor(Math.random() * camels.length);
// calculate the index previous to the current index;
// in case the current index is 0, the previous index will be 11
var previous = (camels.length + index - 1) % camels.length;
// calculate the index next to the current index;
// in case the current index is 11, the next index will be 0
var next = (index + 1) % camels.length;
// if adding 1 to the camel at the current index makes it so that
// the difference with the camel at the previous index is 1 or lower
// the difference with the camel at the next index is 1 or lower
if (Math.abs(camels[index] + 1 - camels[previous]) <= 1
&& Math.abs(camels[index] + 1 - camels[next]) <= 1) {
// go ahead and add 1 to that camel
camels[index]++;
// and decrement the amount accordingly
amount--;
}
}
By adding an outer cycle you can correctly add the remaining part of the amount.
while(amount > 0){
//add amount to camels
}
Check if this Fiddle is what you want to achieve.