JS is changing 2d-array values, might it be another function interfering? - javascript

Short summary: I have written some code that fills up a 2-dimensional array. When I display this array, everything is perfect. Now I give this 2d-array as a parameter to a function. When I call the function inside of
document.getElementById('output').innerHTML = myFunction(int, array);
it shows exactly the right values. However, I don't want to display them, I want to further use them. As the function returns an array (one dimensional), I tried
var my_result_array = myFunction(int, array);
I have also tried push() and pre-defined arrays or accessing just single elements.
The thing is, as soon as I have the function called in my document, the array I am giving to the function as a parameter is changing! I took care that there are no similiar names, but I just can`t figure out, why it is always changing my parameter array, therefore destroying the calculation but working fine if I use it in the document.getElementbyId part.
Any suggestions?
Edit for more code:
I try to keep it short and explainatory. I am creating an empty array with a dimension given by mat_dimension_js
var berechnungs_array = new Array(mat_dimension_js);
for (var i = 0; i < mat_dimension_js; i++){
berechnungs_array[i] = new Array(mat_dimension_js);
}
I then fill this array up with values. If I print the array, everything is fine, the values are where they belong. I then feed this array to myFunction()
Sorry for the mess, I have also tried it without creating an array A again.
I then try to grab the output of myFunction() as told above, but as soon as I do that, somehow the array I have given as a parameter changes.

Arrays in JavaScript are passed by reference, meaning that any changes you do to the array passed inside the function will also be saved in the actual array.
In addition, A = mat_array; does not create a copy of mat_array, but another pointer to it (meaning that both variables refer to the exact same array object internally).
To properly make a copy of a 1D array, calling .slice(0) should do the trick. However, for 2D arrays, you need to do this recursively.
See Javascript passing arrays to functions by value, leaving original array unaltered
What is the most efficient way to deep clone an object in JavaScript?

Related

Removing duplicate random numbers from array

Okay so I'm looping through all the elements on the page (3) that have the class 'possible'. Then I'm creating a variable called 'other' that randomly gets a value from the array otherAnswers. Then I'm taking those values and putting them into the respected elements as text. Only thing is, most of the time the loop selects the same variable from the otherAnswers array (sometimes once, sometimes twice, others three, and rarely none of the time). How do I make sure that once the .each loops through one of the values in the array, it doesn't get it again?
$('.possible').each(function(i, obj) {
var other = otherAnswers[Math.floor(Math.random()*otherAnswers.length)];
$(this).text(other);
//otherAnswers.splice(this);
});
I've tried the commented piece of code but that just removes the values so they don't show up on my page. I have a feeling that it has something to do with the variable 'i' in the function but i'm not sure.
You can do this by taking the following steps:
Before looping, take a copy of the otherAnswers array, to avoid that you destroy it with what follows. For instance, with spread syntax:
var remainingAnswers = [...otherAnswers];
Then -- still before the loop -- shuffle the copied array randomly. Take the shuffle code from here.
shuffle(remainingAnswers);
Finally, inside your loop, access the values from that shuffled array, using the index i you already have:
var other = remainingAnswers[i];

duplicate the object and then update a value in JSON object

I have a array of json objects in jquery . I want to duplicate a object and then replace key value in original object on the basis of if condition . but every time i replaced the value in single object then it replaced the values in both objects . I only want to replace in one i.e original
I have used break and return false statements but dont work.
var index=getIndex(class_id,teacher_id);
finalJson[index]['teacher_name']='asad';
function getIndex(class_id,teacher_id){
for(var it in finalJson){
if(finalJson[it]['class'] == class_id && finalJson[it]['type'] == 'c'){
finalJson.push(finalJson[it])
return it;
}
}
}
please anybody help here is if condition .
Thanks in advance.
When you do finalJson.push(finalJson[it]) you are pushing the reference to old object again in the array. So, any operation done on one reference will be performed on the object to which new reference is pointing to. Which is why you need to create a new object using the properties of old one (using Object.create) and then push it.
replace
finalJson.push(finalJson[it])
with (don't use this option)
finalJson.push(Object.create(finalJson[it]))
or a slower but deep-copy option
finalJson.push(JSON.parse(JSON.stringify(finalJson[it])));
When you copy the object to a new variable, you are creating a reference. You need to create a new object to prevent this, otherwise the changes applied to one object will apply to the other.

jQuery Id Selection and Dynamic Arrays

I have some code I'm struggling with. The good news is the code working as intended for a single instance; after some thought I've decided to feature multiple of these image selectors on a page. This works but the ugly approach of duplicating the code doesn't scale well (e.g. what if you want 50 of these on there?) The snag I've hit is how I can refer to a specific array. Is an array even an ideal solution for this?
The Objective
I have a series of images that a user may select from, up to X amount. The selected image ids are stored in an array and the image is added to a "selected images pool". This occurs by using an onClick for the slider, I obtain the Id from the element attributes. This is where I'm getting stuck.
var dataArray = $(this).closest("[id^=carousel]").data('array');
var slideCounter = $(this).closest("[id^=carousel]").data('counter');
slideCounter = dataArray.length;
The slideCounter returns the length of the string, not the array elements. How can I tell this code to refer to a particular array? See the fiddle for a better idea of the markup and code: jsFiddle
I have no doubt that there is a better approach. I'm relatively new to front end work, I'd appreciate any insights, I've burnt some brain cells on this, thanks!
From looking at your HTML, it looks like when you do this:
var dataArray = $(this).closest("[id^=carousel]").data('array');
what you're trying to do is to read the name of an array with .data() and then somehow turn that name (which is a string) into the array that's in your variable. My guess is that there's probably a better way to structure your code rather than putting javascript variable names in your HTML. I'd probably put a key name in the HTML and then store the arrays in an object where you can access them by that key name at any time.
Without trying to refactor your code, here's an idea for what you were trying to accomplish:
If selectedSlidesIdArray1 is a global variable, then you can do this:
var dataArray = window[$(this).closest("[id^=carousel]").data('array')];
Using the [stringVariable] notation on an object, lets you access a property by a literal string or a variable that contains a string. Since all global variables are also properties on the window object, you can do it this way for global variables.
If selectedSlidesIdArray1 is not a global variable, then you should probably put it in an object and then you can do this:
var dataArray = yourObj[$(this).closest("[id^=carousel]").data('array')];
Instead of trying to translate an arbitrary string into a JavaScript variable of the same name, why not just use another array? You can have nested arrays, which is to say an array of arrays.
Thus, instead of selectedSlidesIdArray1, selectedSlidesIdArray2, etc., you would have one selectedSlidesIdArray with sub-arrays, which you could then pull the index for using a data attribute.

How to assign values to objects through a variable that is just a reference to them?

I couldn't really word the question less vaguely, but I think you will understand...
I am developing a game engine in Javascript, and the Scene object, which is a container of many things, has a method that is supposed to change one array in it, specifically the one holding all the things that can be drawn.
This array is accessed like this:
scene.internals.draw
The problem is, it is referenced many times in the method, and I think that the name/path might change. Naturally, I don't want to change every reference to it in the method each time I change the the array's path, so I did this:
var location = scene.internals.draw;
Now, the actual method code and the algorithm can stay intact, and if the name/path of the array in the scene changes, I only need to change that one line.
And it works pretty well for the most part. I can .push(obj) to it, etc, but at one point, I need to "disect" the array, ie, split it in half, add something, and then put it back together, like this:
buff1 = location.slice(0, i); //First slice of the array.
buff2 = location.slice(i, location.length); //Second slice of the array.
//Add something in between those slices.
buff1.push(ob);
location = buff1.concat(buff2); //Problems here!
This worked well while location was just scene.internals.draw, as it changed the array directly. But now, I assign the new value to the local location variable, not the desired scene.internals.draw one!
Question: how can I, using the = operator, assign values to "real" objects, instead of the variables that contain references to these objects (like location)?
The obvious solution would be this, at the end of the method:
scene.internals.draw = location.slice();
This is OK, the only side effect is that I will have to write the original name twice, and edit it twice, which isn't such a big issue. But, I maybe find myself in other situations where I just might need that functionality, so I'd still like an answer.
There is no assignment by reference in javascript, so you cannot do this. What you are doing is usually mistaken for assignment by reference but it is in fact a copy of a reference value which has implications like this.
You probably have a deeper problem somewhere since you are doing this but I don't wanna get into that.
You could do this:
location.splice( 0, location.length ); //Remove all items in the array
location.push.apply( location, buff1.concat(buff2) ); //Push the buffers into the array
To use your term, there are no "real" objects in Javascript - there are only objects, and the variables that hold references to them.
When you assign to location you're just creating an additional reference to an object. The system has no knowledge of which "real" object it was, nor of any other variables that may hold references to it.
So when you reassign to location you're just overwriting that particular reference. Any other original references to the object will stay pointing just where they were.

handling splice with associative arrays in javascript

I have an array called as wcs declared using var wcs= new Array();.
I do add items like this, wcs[indx] = value. where i will keep on changing the indx value, so at times, my array will be looking like this
wcs[2] ='a'; wcs[5]=')';
when i call the splice method on this array, all the created indices are re-indexed, meaning they become reset from 0...
how to avoid this in javascript & jQuery
Write your own splice method that works the way you want. If you specify the input, processing and expected output, you might get some help with that.
If you simply want a copy of the array, you may be after the concat method.

Categories

Resources