How do I use shift inside a loop? - javascript

When I run this code:
var a = ['a','b','c'];
var b = ['a','b','c'];
for(i = 0; i <= a.length-1; i++){
b.shift();
console.log(b);
}
I expected this output:
['b','c']
['c']
[]
But I get this output:
[]
[]
[]
Why?
And how do I get my expected output?

This is a known problem in Chrome. It's because the console.log doesn't make a copy of what you want to display, it just stores the reference.
As the log isn't updated immediately, but once your function ends and the browser updates the user interface, the log will show the current state of the b variable, not the state when each console.log call was made.
To get the desired ouput you would have to make a flash copy of the state of the variable for each console.log call:
console.log(b.toString());

This is a side-effect of the console.log statements not being printed as the statements are executed. Note that if you replace your console.log with alert, the code works as expected.

Or change the log paramater to be an expression as per my answer to Javascript Funky array mishap
console.log ('' + b);

Related

Can anyone tell me that why the {For} Loop in JavaScript is returning all the values including the very first element of the an array?

var arr = [1,2,3,4,5]
for (var i=0; i<arr.length; i++){
console.log(arr[i]);
}
I ran this code on google chrome console and the output was like this:
1
2
3
4
5
In this code I can see that all the elements are been printed but the very first element of the array which is 1 should not print because the value of [i] has already been incremented to 1 and so 2 should be printed instead of 1.
Can someone tell me why is this happening ?
I think you are getting it wrong here. In for loop, we have
for(initialization, condition, change) {
// body
}
So, it workes in this sequence
initialization -> condition -> body -> change
PS: It will go to body if condition evaluates to true

Issues with populating arrays from csv(dsv) parsing

I am quite new to javascript, basically using it for the first time to write a histogram plotter application. My issue is, I am importing a data file and ideally sending (some of) the entries into an array. Problem is that once I do that, I have troubles accessing the entries in my array.
How could I fix that? Posting the code below in case it helps.
Thank you!
let filename = 'uploads/testdata.dat';
const data_e = new Array();
d3.dsv(" ",filename, (event)=>{
data_e.push(event.mass);
return data_e
})
console.log(data_e);
Which outputs
Array []
​
0: "734.770828169"
​
1: "85.0912893849"
​
2: "87.383924186"
​
...
However if I wanna get a value:
console.log(data_e[0]) //output: undefined
Edit1: the values I'm pushing are in console.log(event.mass).
output:
734.770828169 analyzer.php:19:12
85.0912893849 analyzer.php:19:12
87.383924186 analyzer.php:19:12
(...)
Edit2: If I call console.log(data_e) inside the dsv function I get a line for each iteration while my array gets filled, ending with
Array(7178) [ "734.770828169", "85.0912893849", "87.383924186", "1274.99805502", "91.5349415148", "80.2766459668", "1396.69489276", "91.5584443363", "94.52017453", "1582.29197222", … ]
Which is, indeed the object I want to get. But what if I want to carry that outside the function dsv(), so that I get the same output as above?
Edit3: Calling console.log(JSON.stringify(event.mass)) gives:
again, one line for each 'iteration' (I think), and it makes sense. I just want to use the full array outside that function (or maybe it's just a silly thing to do .-.)
"734.770828169" analyzer.php:19:12
"85.0912893849" analyzer.php:19:12
"87.383924186" analyzer.php:19:12
"1274.99805502" analyzer.php:19:12
(...)
Do not use return inside the loop, because you then leave it immediately. Whatsmore, I think d3.dsv() is an asynchronous function. Means your console log outside this method must return undefined as Javascript does not wait for d3.dsv() to finish. And your Array data_e is currently undefined.
let data_e = new Array();
Instantiate it this way and you'll see, that console.log() will output [] instead of undefined.
let data_e = [];
d3.dsv(" ",filename, (event)=>{
// your code
})
console.log(data_e);
Actually, I could not find a manual about how to get a trigger when d3.dsv() is finished. But fo the start try it this way. It's not perfect but it's only supposed to show you that it actually works;
let filename = 'uploads/testdata.dat';
const data_e = new Array();
// run the filter
d3.dsv(" ",filename, (event)=>{
data_e.push(event.mass);
})
// wait 2 seconds, then show the array in the console
setTimeout( () => {
console.log(data_e);
}, 2000);

extra output after loop

I am learning JavaScript on Codecademy. I am finding so many outputs like below when I use while loop.
for (var i=0; i<5; i++){
console.log("Dhanu identify problems and solve them");
}
var loop = 0;
while(loop<5){
console.log("Do some more");
loop++;
}
I am getting an unwanted output in the last line as 4.
The output you get is simply console.log which logs the last known value of the 'loop' variable: (here in firefox):
It's absolutely not related to your code and you don't have to worry about that.
As stated in another answer, debug console use to log the result of the last line (probably because they are meant to debug).
For example the statement "i = 1" evaluates to "1":
while the statement "var i = 1;" evaluates to "undefined", hence logging "undefined"
you can observe the same behavior by invoking eval on those statements:
You're seeing that because the last statement in your while loop is loop++, which "returns" the current value of loop. This is just a side effect of running code in a console like this. Consoles are basically read-execute-print-loops (REPL), and so they need something to print. If you ran this as a script in a webpage you would not see 4
when you write any statement in developer console then last returned value will be printed...
for example
var a;
it prints undefined on console.
a = 10;
it prints 10 on console.
a = 10; a = a + 5;
it prints 15 on console.
simply when we assign any values or increment or decrement numbers then it returns value after performing that operation...
so, in the above or below code
var loop = 0;
while(loop<5){
console.log("Do some more");
loop++;
}
finally loop++ is 4.

How do I print While Loop?

Im trying to print the objects in my Array 'ana' but I keep getting a number 2 after the contents are printed. How do I remove the number 2?
var ana = ["I", "Love", "my mother"];
var a = 0;
mother = ana.length;
while(a < mother) {
console.log(ana[a]);
a++;
};
Logs:
I
Love
my mother
2
Don't worry. This is your interpreter behavior. Your code is not actually printing 2. You are seeing 2 because your javascript interpreter prints the value of last assigned value.
In your code, a++; executed in the last loop will return 2(because x++ returns x and then increments it) in the last loop thereby the return value of your whole expression is 2.
You must be printing 2 somewhere else after this loop, your code will only print 'I Love my mother'.. also, there shouldn't be any ; at the end of while loop.
See the demo here
You can move the a++ inside console.log to stop showing it. Like this
console.log(ana[a++]);
The value 2 was getting printed as the return value of your code, which is the last value that a gets.

Keep losing incremental variable within for loop

I've been fiddling with this for way too long and can't seem to get it working as it should.
The problem I'm having is that I'm losing the value of my incremental variable in a for loop, specifically when it goes in to the if statement that I have inside of it. Ideally i want to iterate through an array until I find the correct value, attach a variable to that value and use it outside of the for loop. This is the structure of the array I'm working with.
var dXId = [
{url:"url1", dId:"id1"},
{url:"url2", dId:"id2"},
{url:"url3", dId:"id3"}
];
And here is the loop that I'm running everything through:
for(i=0; i < dXId.length; i++) {
if (dXId[i].url == currentUrl){
var dataXuId = dXId[i].dId;
break;
}
}
The incremental 'i' variable always reverts back to 0 within the if statement. It's odd, the dXId[i].url comes up correctly, but the dXId[i].dId pulls the first entry and 'i' seems to be lost after that. I'm sure there is a very simple solution to this, but javascript is something that I just always seem to have trouble with.
You are setting dXId[i].url = currentUrl inside your for loop instead of comparing with '=='. That could be part of the problem.
EDIT
As suggested by Eric...
The == Operator is to loosely compare the value of things, and the === is to strictly compare the value and type of things.
Examples:
Given x=10;
x == '10' // true
x == 10 // true
x === '10' // false
x === 10 // true
You have mistake in your if syntax.. you are assigning value of currentUrl to variable dXId[i].url
if (dXId[i].url = currentUrl){
...
}
It should be changed to === to compare string values.
if (dXId[i].url === currentUrl){
...
}
After that, it works! Example also here: js fiddle
Thus, it is rather funny that JavaScript lets do such things in the first place: Assigning value to a variable in if block should definitely not be allowed.
For example consider the following snippet:
var foo = 1, // change to 0 and console.log will not be displayed
bar; // undefined
// Assigning value of foo to bar
if (bar = foo){
// Will print out 1
console.log("bar is: " + bar);
}
Will result to a printing following output to the console:
bar is: 1
The reason being that if (bar = foo){ is equals to if (1){ which allows program to continue inside the if block :) ... if value of 0 is used for foo, console.log will not be displayed. (This is the behaviour at least which I tested using google chrome.)
Example about this in js fiddle

Categories

Resources