Javascript isn't setting the Array - javascript

I am not getting any errors. When you look at the console.log()'s outputs, the first one gives me the array, and when I open up the 2nd one, it says the array is empty! It's almost as if it was never set. The array I'm checking for is .axes.
I can directly access it, but then I can't see it when I expand the object.
This is for the most important thing in my life and the universe is trying to stop me.
for(i=0; i<$.count; i+=1){
h = chain[i];
h.axes = [ chain[0] ];
if (i==3){
console.log('Direct_AXES',h.axes);
console.log('Direct_H',h);
}
chain[0].dna.push(h);
}

As far as I can help you. This works like a charm.
var chain = [{},{},{},{},{}];
for(i=0;i<chain.length;i+=1){
h = chain[i];
h.axes = [ chain[0] ];
if (i==3){
console.log('Direct_AXES',h.axes);
console.log('Direct_H',h);
}
// chain[0].dna.push(h);
}
I added an array with four empty objects (so the code would somehow run). And I commented the last line of the loop because obviously I would run into an error.
Everything is working fine. So the conclusion here is that there is an error in the part you didn't post, because everything is working as expected.
Both logs do print the array and the whole object h containing the axes array.

Related

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);

How do i fix the wrong integration of an automatic transfer of rows between sheets?

What I'm trying to accomplish is:
have a data input sheet called 'data' (its data is fed by a form)
script moves the information from data to sheet1/sheet2/.../sheetn (according to a string that is to be found in column 3)
script also deletes moved rows
I think the deleteRow command works fine, i suspect the culprit being the detection of the string in the array.
I've already used the search a lot, tried a few codes and I've identified this as the most probable candidate (its by cooper), as it's almost doing what i need it to do.
I tried logging a bit, but unfortunately i dont know too much about coding yet. Currently im learning by trial and error.
If i log for vals[i][2] i only get 1 string, instead of a few from my example input.
When i set only one targetsheet (sh1) and target-term it works. but when i extend it it doesnt work anymore.
{
var ss=SpreadsheetApp.getActive();
var sh0=ss.getSheetByName('Data');
var rg0=sh0.getDataRange();
var sh1=ss.getSheetByName('Applesheet');
var sh2=ss.getSheetByName('Banana');
var sh3=ss.getSheetByName('Cherry');
var vals=rg0.getValues();
Logger.log(vals)
for(var i=vals.length-1;i>0;i--)
{
if(vals[i][2]=='Apple')
Logger.log("PV Abfrage -", vals[i][2])
{
sh1.appendRow(vals[i]);
sh0.deleteRow(i+1);
}
if(vals[i][2]=='Banana') //also tried with else if here
{
sh2.appendRow(vals[i]);
sh0.deleteRow(i+1);
}
if(vals[i][2]=='Cherry')
{
sh3.appendRow(vals[i]);
sh0.deleteRow(i+1);
}
}
}
My code moves rows that dont contain any of the terms.
It's also supposed to only move rows that contain this term, but its doing so super unrealiably.
I think all rows get appended to Applesheet, rows that contain banana are moved to banana but the ones with cherry wont.
Im definitely not experienced enough to judge, but this code seems a bit unreliable, because even my test version with just one if fails to perform the way i want it to.
Issue:
Your first if statement is forced to return true by the Logger.log() you've included between if and {. As soon as you remove it, your code functions exactly as you're expecting.
Example:
If we run the following script:
var check = ['Apple', 'Pear', 'Fruit'];
for (i = 0; i < check.length; i++) {
if (check[i] === 'Apple') {
console.log('Found!');
}
}
We're looping through an array, and logging "Found!" for every time the item in the array is found. This is the same way your script works. It works as expected, "Apple" is only found once in the array, so the log looks like this:
Found!
As soon as we put a log between the if and the {, like so:
var check = ['Apple', 'Pear', 'Fruit'];
for (i = 0; i < check.length; i++) {
if (check[i] === 'Apple')
console.log("Oops!")
{
console.log('Found!');
}
}
We get the following:
Oops!
Found!
Found!
Found!
Summary:
Make sure to only include your conditions for the if statement between your if and {, adding anything else can return false positives like you've experienced today.
Reference:
JavaScript if Statements

How is it possible to have an array with length 0 but has content?

I have the following test code:
console.log('AA',slider);
console.log('AB',slider.length);
it returns the following in chrome console.
AA Array[53]
AB 0
i added test code because slider[5] always came back with undefined even though the console shows there is a value there.
here is a simplified version of initialisation script. entire code is pretty long and Slider is an object. Code for object is working the test script is later on trying to manipulate specific slider positions based on ajax return data.
var slider=[];
for (var uid=1;uid<50;uid++) {
slider[uid]=new Slider(.........);
}
var slider={};
for (var uid=1;uid<50;uid++) {
slider[uid]=new Slider(.........);
}
returns
AA {
1:{m
a: ....,
b: ....,
c: ....,
g: ....,
h: ....
},
2: .....
gets all the way up to 49
Ok i figured out the problem and hopefully this helps others.
After going through the code here is a much better example of initialization
var slider=[];
setInterval(function(){
for (var uid=1;uid<50;uid++) {
slider[uid]=new Slider(.........);
}
},500);
console.log('AA',slider);
console.log('AB',slider.length);
the array is indeed empty at the time the console log commands are executed but apparently the first line records reference to the object and not current state. So when I look at the log which is always going to be more then half a second later it shows data being there.

object with array type string causing a typeError

The best way to explain this is just to show you.
var condition = 70;
var formnames = new Array("wheelcheckbox1", "wheelcheckbox2","spokecheckbox","spokecheckbox2","tirecheckbox","tirecheckbox2","tirecheckbox3");
formnames.forEach(function(entry) {
console.log(obj.entry);
if(obj.entry == "") {
condition = condition - 10;
}
});
as you can see I used the console log to show how it needs to work
as that works perfect, however, using the array causes an error as
they're strings and not what the obj wants, it wants text without it being a string.
Any ideas?
for..in should not be used to iterate over an array. Consider using forEach instead.

console.log/console.dir showing last state of object, not current

I want to log how my array/object is changing with new steps of loop. Console.log does this bad. It shows only last state of object everywhere. For example:
var a = {};
console.log(a); // {bob1: 0, bob2: 0}
a.bob1 = 0;
console.log(a); // {bob1: 0, bob2: 0}
a.bob2 = 0;
console.log(a); // {bob1: 0, bob2: 0}
I found there, on so, another command: console.dir. It is working properly in same example. It shows states of object correcly.
Look this example. This command works perfect: http://jsfiddle.net/RLzVV/
Now, look my code pls. All output is in console. http://jsfiddle.net/3BDs7/4/
This is aStar algorithm. Take a look on this part (neighbor 3 loop <--- neighbor 3 start ---> this code is situated here <--- neighbor 3 stop -->) in console. Lanes, which output this to console are 105-113:
new openset length: 2
openset after adding new vertex
**shows 1 element, but length is 2**
It shows length is 2, but shows only 1 element. But! Seems to me algo is working correctly (it is popping another element, which is hidden on this step after). Why this bug appears? Did I did something wrong? Seems to me, everywhere only last state of array shown, not current:( help me please.
That's a known issue -- sounds like you are running under Chrome.
The easiest work-around is to JSON encode the value as you log in.
console.log(JSON.stringify(a));

Categories

Resources