For loop creating infinite object tree - javascript

I have 2 for loops creating an object:
function newImage(){
image = {};
var temp = {}
for(i=0;i!=250;i++){
temp[i] = {};
}
image = temp;
for(i=0;i!=250;i++){
image[i] = temp;
}
}
This should create an object with 250 values, each being an object that contains 250 objects. However, it creates an object that creates 250 values, fills those with 250 values, and loops this for a while. I haven't found the end of the tree, but it doesn't freeze leading me to believe that it is finite. I've checked the iterations up to 50 and it works all the way (it doesn't make the long tree). It seems as if it is happening during the last iterations. Here's the full thing.

var temp = {}
for(i=0;i!=250;i++){
temp[i] = {};
}
The lines above create an object and populate it with 250 other objects (so far so good).
Then image = temp; sets the image (global) variable to be temp (so image now contains 250 objects) then:
for(i=0;i!=250;i++){
image[i] = temp;
}
This replaces each of those 250 objects (overwriting the previous assignments) with a reference to the parent object so the object the has 250 attributes which all refer to itself.
Effectively what you wrote is:
image = {};
for ( var i = 0; i < 250; i++ )
image[i] = image;
It then appears that you have an infinite tree of objects whereas you only have a single object which has many attributes that refer to itself so whenever you descend to a child you end up back at the parent (and expanding the object hierarchy in the browser makes it appear to be an infinite tree when its actually only showing the same object over and over).
What you probably meant to write is:
function newImage(){
var temp = {};
for( var i=0; i < 250; i++){
temp[i] = {};
for( var j=0; j<250; j++){
temp[i][j] = {};
}
}
return temp;
}

Your problem is that when you assign image to temp, any further edits on either of those objects is reflected on the other object.
Try the following code instead:
function newImage(){
image = {};
var temp = {}
for(i=0;i!=250;i++){
temp[i] = {};
}
for(var item in temp){
image[item] = temp[item];
}
for(i=0;i!=250;i++){
image[i] = temp;
}
}

Related

Create multiple instances of an object (by adding incremental numbers to it's name) and addChild to stage

I'm using Canvas/javascript (createjs) and am having difficulty calling an instance or adding a child to stage of a cloned shape (via an array using a for loop adding incremental numbers).
var myShape = new createjs.Shape();
myShape.graphics.f("white").rr(0, 0, 300, 300, 12);
myShape1 = myShape.clone();
myShape2 = myShape.clone();
myShape3 = myShape.clone();
//var arr = [null,cellFlasha1, cellFlasha2, cellFlasha3, cellFlasha4];
var arr = [];
for (var i = 1; i <= 4; i++) {
arr.push(["myShape"+i]);
}
stage.addChild(arr[1]);
I can't seem to add and instance to the stage. It does work when I use the array that has been commented out though. Could it be how i've combined a string and value when I push it to the array as an object?
I know I could just add it to stage by doing stage.addChild(myShape1); etc.. but I want to do it via a loop as there as there will be many more instances to come and similar scenarios (I intend to loop how I add the clones too so the number of objects can just be defined once)
I'm relatively new to javascript so my terminology may not be great. Many thanks in advance. Any help would be much appreciated!
Muzaffar is correct that you can access those variables via the window object, but it is generally a code smell to rely on globals for this kind of thing. Is all you need to get an arbitrary number of those shapes into an array? If so, why not try something like this?
function cloneShapeIntoArray(shape, num) {
var shapeArray = [];
for (var i = 0; i <= num; i++) {
shapeArray.push(shape.clone());
}
return shapeArray;
}
function addShapesToStage(shapes, stage) {
for (var i = 0; i <= shapes.length; i++) {
stage.addChild(shapes[i]);
}
}
var myShape = new createjs.Shape();
myShape.graphics.f("white").rr(0, 0, 300, 300, 12);
var shapes = cloneShapeIntoArray(myShape, 3);
// You can do some extra stuff to the shapes here, eg you could make each one a different scale
// shapes[0].scale = 1
// shapes[1].scale = 1.5
// shapes[2].scale = 2
addShapesToStage(shapes, stage);
That allows you to easily control how many copies you want, and does not pollute the global namespace.
Yes you can do this with "window" global object. Something like this
for(var i=1; i<=4; i++) {
window['myShape'+i] = myShape.clone();
}
var arr = [];
for (var i=1; i<= 4; i++) {
arr.push(window['myShape'+i]);
}
For more detail you can see here:
Use dynamic variable names in JavaScript

When using strings with numbers at the start in an array key (Indesign 2017, extendscript) they don't get added to the array

Observe:
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks[linkName] = new Array;
}
I would have expected the result to be the array groupedLinks to be filled up with 5 new keys, the value would be 5 empty arrays.
The actual result in extendscript would be ... grouplinks ... empty.
If I would change this example to be:
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "notgonnawork" + i;
groupedLinks[linkName] = new Array;
}
It would work perfectly. The only change is the missing "59" at the start of the string used for the array key.
Note that this works perfectly when I run it in console for chrome or firefox. It seems to be indesign and/or extendscript fooling around.
Anything have any ideas why ? I've meanwhile worked around the problem but I'm intrigued.
I would have expected the result to be the array groupedLinks to be filled up with 5 new keys, the value would be 5 empty arrays.
That's exactly what it does, but the way you're viewing the data is likely concealing it because you're not using the proper data structure. Also, property access won't work without using [] because identifiers may not start with a number, so you'd need:
groupedLinks["59notgonnawork0"]
What you're doing isn't meant for arrays, which are expecting sequential numeric indices (though they can technically be assigned other properties too). The type of structure you should be using is a plain object instead.
var groupedLinks = {};
for(var i = 0; i < 5; i++) {
const linkName = "59notgonnawork" + i;
groupedLinks[linkName] = new Array; // Array? plain Object? Depends on its use.
}
Why not trying to push the value in the array on each iteration.
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks.push(linkName);
}
ExtendScript Arrays are great for stocking data per indeces. If you need key/values objects, why not use… Objects ?
var groupedLinks = {};
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks[linkName] = "Whatever…";
}
alert( groupedLinks["59notgonnawork0" ] ); //"Whatever…"

Javascript, adding multiple arrays to an array with a for loop

What is the best way to consolidate this code? As it is, it works perfectly, but it needs to go up to maybe 40-50 items long, so it needs to be shortened dramatically, (I assume, with a for loop).
I'm pretty much a novice when it comes to Javascript, and trying to add arrays to an array with a loop is confusing me immensely.
The "vac1.", "vac2." ...etc, variables are used later on in the code to add pointers onto a Google Maps map.
var x = count.count; // x = a value that changes (between 1 & 50)
if(x == 1){
locations = [
[vac1.vacancy_title, vac1.vacancy_latlng, vac1.vacancy_url, vac1.vacancy_location]
];
}
if(x == 2){
locations = [
[vac1.vacancy_title, vac1.vacancy_latlng, vac1.vacancy_url, vac1.vacancy_location],
[vac2.vacancy_title, vac2.vacancy_latlng, vac2.vacancy_url, vac2.vacancy_location]
];
}
if(x == 3){
locations = [
[vac1.vacancy_title, vac1.vacancy_latlng, vac1.vacancy_url, vac1.vacancy_location],
[vac2.vacancy_title, vac2.vacancy_latlng, vac2.vacancy_url, vac2.vacancy_location],
[vac3.vacancy_title, vac3.vacancy_latlng, vac3.vacancy_url, vac3.vacancy_location]
];
}
...etc etc...
I have tried using a for loop, but it doesn't work and I have no idea if I am anywhere close to figuring out how to do it correctly.
var x = count.count;
locations = [];
array = [];
for (i = 0; i < x; i++) {
array = [vac[i].vacancy_title, vac[i].vacancy_latlng, vac[i].vacancy_url, vac[i].vacancy_location];
locations.push(array);
}
Any help or advice would be greatly appreciated!
Thank you.
You need to consider them as a string:
var x = 5;
locations = [];
array = [];
for (i = 1; i <= x; i++) {
array = ['vac'+i+'.vacancy_title', 'vac'+i+'.vacancy_latlng', 'vac'+i+'.vacancy_url', 'vac'+i+'.vacancy_location'];
locations.push(array);
}
console.log(locations);
Create an array vac and use your previous code :
var x = count.count;
locations = [],
array = [],
vac = [ /* vac1, vac2, ...., vacn */ ];
for (i = 0; i < x; i++) {
array = [vac[i].vacancy_title, vac[i].vacancy_latlng, vac[i].vacancy_url, vac[i].vacancy_location];
locations.push(array);
}
You could use eval for the variable name and build an new array with another array for the wanted keys.
Basically you should reorganize yor program to use a solution without eval. An array could help. It is made for iteration.
var x = count.count,
i,
keys = ['vacancy_title', 'vacancy_latlng', 'vacancy_url', 'vacancy_location'],
locations = [];
object;
for (i = 1; i <= x; i++) {
object = eval('vac' + i);
locations.push(keys.map(function (k) { return object[k]; }));
}
Group the vac* elements in an array and then use slice to cut out as many as you want, then use map to generate the result array:
var vacs = [vac1, vac2 /*, ...*/]; // group the vacs into one single array
var x = count.count; // x is the number of vacs to generate
var locations = vacs.slice(0, x).map(function(vac) { // slice (cut out) x elements from the arrays vacs then map the cut-out array into your result array
return [vac.vacancy_title, vac.vacancy_latlng, vac.vacancy_url, vac.vacancy_location];
});
Because any global variable is a property of the global object :
var vac1 = "whatever";
console.lof(window.vac1); // => logs "whatever"
console.lof(window["vac1"]); // => accessed as an array, logs "whatever" too
You could use the global object and access it as an array to look for your vac1, vac2, vac3 variables :
var x = count.count, i;
locations = [],
array = [],
var globalObject = window; // or whatever the global object is for you
var vac; // this will be used to store your vac1, vac2, etc.
for (i = 0; i < x; i++) {
vac = globalObject["vac"+i]; // the "vac" + i variable read from the global object
if (vac !== undefined) {
array = [vac.vacancy_title, vac.vacancy_latlng, vac.vacancy_url, vac.vacancy_location];
locations.push(array);
}
}

Copy array --> stack or heap overflow?

I have an array named globalArrayAllTrades as you see below. I simply like to INVERT the date in a new copy of the array. So I loop through, create a new object and add it to the new array - simple.
Then function does exactly as expected. BUT if the array contains too many objects the code fails with a "FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory".
My laptop has 8 GB of memory...When the NODEJS process crashes it uses about 1.5 GB and about 70% of of totally amount of available memory is used.
I do run the NODEJS app with the parameter: --max_old_space_size=5000 which normally fixes every thing. But not this one and i have tried MANY different ways to code the same function - BUT each and every time - it fails...unless the original array is smaller.
How can I fix this issue?
function invertTrades(){
var original = globalArrayAllTrades.slice();
globalArrayAllTrades.length = 0;
globalListAllTrades.length = 0;
for(var i = 0; i < original.length; i++){
var objS = original[i];
var objE = original[original.length-1-i];
var objInv = new TradePoint(objS.number, objS.matchdate, objE.price, objE.size, objE.issell);
globalArrayAllTrades.push(objInv);
globalListAllTrades[objInv.matchdate] = objInv;
}
}
You can save some memory by making original just contain the properties you need to invert, not the whole TradePoint object. Then you don't need to construct new TradePoint objects, you can modify them in place.
var original = globalArrayAllTrades.map(function(trade) {
return {
trade.price,
trade.size,
trade.issell
};
}).reverse();
globalArrayAllTrades.forEach(function(trade, i) {
trade.price = original[i].price;
trade.size = original[i].size;
trade.issell = original[i].issell;
});
And since all the objects were modified in place, there's no need to update globalListAllTrades.
Another way is to swap the price, size, and issell properties in place between the pairs of elements:
var midpoint = Math.floor(globalArrayAllTrade.length/2);
for (var i = 0; i < midpoint; i++) {
var objS = globalArrayAllTrades[i];
var objE = globalArrayAllTrades[globalArrayAllTrades.length-1-i];
var temp = objS.price;
objS.price = objE.price;
objE.price = temp;
temp = objS.size;
objS.size = objE.size;
objE.size = temp;
temp = objS.issell;
objS.issell = objE.issell;
objE.issell = temp;
}
Have you considered just doing this?
// Copy array and then reverse it
var newArray = [].concat(original).reverse();
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
I would suggest avoiding to copy that array:
function getInverse(i) {
var objS = globalArrayAllTrades[i];
var objE = globalArrayAllTrades[globalArrayAllTrades.length-1-i];
var objInv = new TradePoint(objS.number, objS.matchdate, objE.price, objE.size, objE.issell);
globalListAllTrades[objInv.matchdate] = objInv;
return objInv;
}
function invertTrades(){
globalListAllTrades.length = 0;
for (var i = 0, l = Math.floor(globalArrayAllTrades.length/2); i < l; i++) {
var j = globalArrayAllTrades.length-1-i;
var a = getInverse(i);
var b = getInverse(j);
globalArrayAllTrades[i] = a;
globalArrayAllTrades[j] = b;
}
}

how to access and sort 2d array in javascript

I'm writing a script to initalize 2d array in javascript by reading txt file. Here are some portions of my code
var neighbor = {};
var temp = new Array();
neighbor[nodemap[ temparray[0]]] = temp; //nodemap[ temparray[0]] is an integer
neighbor[nodemap[temparray[0]]]. push(nodemap[temparray[1]]);
neighbor[nodemap[temparray[0]]]. push(nodemap[temparray[2]]);
.... // continue to add value
Then I want to access and sort the array, like this
for (var i = 0; i < n_count; i++);
{
for (var k = 0; k < neighbor[i].length; k++);
neighbor[k].sort(function(a,b){return a - b})
}
However, I got the error that neighbor[i] is unidentified. Could you please show me how to fix that?
Your neighbor "array" is actually an object literal. So the way you should loop over neighbor is:
for (var key in neighbor) {
var cur = neighbor[key];
cur.sort(function (a,b) {
return a - b;
});
}

Categories