array changing values for a strange reason - javascript

Given the code below:
function createJson() {
var varry = new Array();
varry = x;
for (i=0 ; i < arry.length ; i++) {
if (arry[i]["questionVisibility"] == "1"){
if (arry[i]["questionType"] != 3) {
varry[i][1] = document.getElementById('te'+arry[i]["id"]+'et').value;
} else {
e = document.getElementsByName("te"+arry[i]["id"]+"et")[0];
p = e.options[e.selectedIndex];
varry[i][1] = p.text;
}
}
}
console.log(x);
console.log(varry);
Where X is an array that has been created like this(inside a different function):
x = document.getElementById("jsonData").value;
x = JSON.parse(x);
x = x[0];
x = x.data;
x = JSON.parse(x);
Can anyone explain me why when i call the createJson() function, the x array is changed? (x is already created when the createJson() is called)
Thanks in advance!

it's because of line
varry = x;
assigning an array to variable creates kind of reference of original value so when you modify varry it also modifies x
if you want to get a copy of x into varry without reference use
array.slice() like this:
varry = x.slice();
this will insert values from x into varry without creating 'reference' to original array

Related

Javascript changing value in multidimensional array

I try to to fill a multidimensional Array with the content from an Json file.
The problem is, I can´t update the content in the Array:
if(j>i && hoursYy == hoursY && secondsX == secondsXx){
wocheArray[i].count = wocheArray[i].count + 1;
}
My goal was, that "count" counts up, every time I find a duplicate in my JSON file. I couldn't´t find an answer online jet.
just in case, here is the whole code:
var myweek;
var x;
var y;
var id;
var count;
var wocheArray = [];
function preload(){
myweek = loadJSON("data/data.json");
}
function setup(){
createCanvas(windowWidth, windowHeight);
background(0);
//SAVE IN WOCHEARRAY
for (var i = 0; i < myweek.woche.length; i++) {
hoursY = myweek.woche[i].stunden;
secondsX = myweek.woche[i].sekunden;
for (var j=0; j< myweek.woche.length; j++){
hoursYy = myweek.woche[j].stunden;
secondsXx = myweek.woche[j].sekunden;
if(j>i && hoursYy == hoursY && secondsX == secondsXx){
wocheArray[i].count = wocheArray[i].count + 1;
}
else {
x = myweek.woche[i].stunden;
y = myweek.woche[i].sekunden;
id = myweek.woche[i].person;
count = 0;
}
wocheArray[i] = {x, y, count, id};
}
}
console.log(wocheArray);
}
The problem reside here :
wocheArray[i] = {x, y, count, id};
If you check your code you would find that this part is overriding.
Consider your case: If a duplicate is found.
Then what your for loop will do:-
1.) Set var count = 0;
2.) [Skipping to If condition where is the procedure to check]
//IF match found (at j = 2 location, and i = 1)
//then what happen is :
if(2>1 && hoursYy == hoursY && secondsX == secondsXx){
wocheArray[1].count = wocheArray[1].count + 1;
// from here the count of wocheArray[1] would be increased by 1, Suppose 1.
}
3) In else block it will again set count = 0;
4) Again you are trying to set the values of wocheArray[1] = {x, y, count, id}; //now wocheArray[1] count is set to 0.
So from here, you can see you are updating the values or overriding them which creating the undesired result.
You should not call this outside wocheArray[i] = {x, y, count, id};
You must call it inside else block to make it work correctly.
else{
x = ....
....
....
count = 0;
wocheArray[i] = {x, y, count, id};
}
However, I am curious about the using of count = 0; inside else block as it does nothing here and var count =0; inside the for block which just re-initializes count variable which is wasting memory or not a good practice. According to shown code sample.
If you format your code a bit better, you will see that
wocheArray[i] = {x, y, count, id};
is outside your if else. So wocheArray[i] is overwritten at the end of every loop.

Javascript: an array in While loop isn't changing when it should

I have a while loop that's working fine. Inside it is an array push. yes this part works perfectly until the while loops completes. All of this is inside another while loop what has an increment change. the increment affects the array in hopes to re-write it completely. what ends up happening is that it stays stuck on the first version of the array, and everything else in later coding can't call on the second version of the array.
var arrayname = [];
var increment = 0;
var var1 = 0;
var x = 0;
var y = 0;
var z = 0;
outerloop == 0;
while(outerloop == 0){
endloop = 0;
while (endloop == 0) {
arrayname.length = 0;
randomFunctionThatCreatesThe123variables();//in here 'increment' changes output.
x = (1 + 2 + 3); //above function's summed result
y = 25; //static base number
alert(increment);
z = (increment + y);
if (x == z)
arrayname[array.length] = [1,2,3];
if (x == 500)
endloop = 1;
}
testloop = 0;
while (testloop == 0){
otherRandomFunctionsThatTestArray();//this loops the same functions on each subarray
if (var1 == arrayname.length) {
testloop = 1;
var1 = 0;
tar = ++increment;
}
}
if((increment + y) == 700)
outerloop = 1;
}
my goal is that the testloop functions test the array, then when endloop recreates the array on the next cycle, it will use the newly incremented affected array. but all that happens is:
if array not cleared:it keeps cycling the tests throught the same array.
if cleared with arrayname.length = 0; the tests use the new increment to find the new array and but finds it undefined.
the alert proves the increment is being properly read.

scriptProcessorNode.onaudioprocess not able to access global variables

I am building class around a scriptProcessorNode oscillator. I have wrapped my onaudioprocess event handler in a function Gendy.prototype.process. I can access global variables and functions from within this wrapper function, but they are not accessible from within the onaudioprocess function.
I devised a work around for the properties, to redefine them in the wrapper function, but this doesn't work when trying to call another method, a random walk method, with this.walk().
Here is my code:
Gendy.prototype.process = function(){
var point = 0;
var index = 0;
var y = 0;
var breakpoint = this.breakpoint;
var freq = this.freq;
var walk = this.walk();
this.scriptNode.onaudioprocess = function(audioProcessingEvent){
var outputBuffer = audioProcessingEvent.outputBuffer;
var outputData = outputBuffer.getChannelData(0);
for(var j = 0; j < outputData.length;j++){
// linearly interpolate between the new breakpoint positions
// get the interp point by comparing index to the x distance
var lerp = (index - breakpoint[point].x) / (breakpoint[point+1].x - breakpoint[point].x);
y = lerp * (breakpoint[point+1].y - breakpoint[point].y) + breakpoint[point].y;
if(point < breakpoint.length && index >= breakpoint[point+1].x) {
point++;
}
outputData[j] = y;
index+=freq;
if(index >= breakpoint[breakpoint.length-1].x){
index = 0;
point = 0;
walk();
}
}
}
}
This makes sound, but returns the errors:
Uncaught TypeError: walk is not a function
for few lines and then
Uncaught TypeError: undefined is not a function
forever.
Is this a bug with the scriptProcessorNode? Any insight would be appreciated!
no bug in scriptProcessorNode, the issue is the below line:
this.scriptNode.onaudioprocess = function(audioProcessingEvent){
the this varible inside the onaudioprocess would refer to this.scriptNode object by default, you can handle it in one of two ways:
Use bind( as you have done in your answer):
this.scriptNode.onaudioprocess = function(audioProcessingEvent){
...
}.bind(this)
use a local variable to hold the value of this, and use that local variable in place of this:
var self = this;
this.scriptNode.onaudioprocess = function(audioProcessingEvent){
...
I was able to access this from within the onaudioprocess function by attaching .bind(this) to it.
Here is the code:
Gendy.prototype.process = function(){
this.scriptNode.onaudioprocess = function(audioProcessingEvent){
var outputBuffer = audioProcessingEvent.outputBuffer;
var outputData = outputBuffer.getChannelData(0);
for(var j = 0; j < outputData.length;j++){
// linearly interpolate between the new breakpoint positions
// get the interp point by comparing index to the x distance
var lerp = (this.index - this.breakpoint[this.point].x) / (this.breakpoint[this.point+1].x - this.breakpoint[this.point].x);
this.y = lerp * (this.breakpoint[this.point+1].y - this.breakpoint[this.point].y) + this.breakpoint[this.point].y;
if(this.point < this.breakpoint.length && this.index >= this.breakpoint[this.point+1].x) {
this.point++;
}
outputData[j] = this.y;
this.index+=this.freq;
if(this.index >= this.breakpoint[this.breakpoint.length-1].x){
this.index = 0;
this.point = 0;
this.walk();
}
}
}.bind(this);
}

how to search through object data? [duplicate]

This question already has answers here:
How do I enumerate the properties of a JavaScript object? [duplicate]
(14 answers)
Closed 8 years ago.
I have multiple objects with x and y values,
var object = new Object();
object.one = new Object();
object.one.x = 0;
object.one.y = 0;
object.two = new Object();
object.two.x = 1;
object.two.y = 1;
How would you determine which object has an x and a y that = 1?
You could pass is an x and y value to a function.
function = function(x,y) {
// code to find which objects x and y = parameters
};
Maybe "x in y" loop is what you are looking for. Here is how you do it:
for(var p in object) // String p will be "one", "two", ... all the properties
{
if(object[p].x == 1 && object[p].y == 1) console.log(p);
}
Here is more info http://www.ecma-international.org/ecma-262/5.1/#sec-12.6.4 .
I'd use something along the lines of:
var findObject = function(object, x, y) {
for(var subObject in object) {
if(object[subObject].x === x && object[subObject].y === y)
return object[subObject];
}
};
Then using findObject(object, 1, 1) will give you the object with x and y equal to 1.
See this fiddle.
search = function(x, y) {
for (var p in object) {
if (object[p].x == x && object[p].y == y) console.log(p);
}
}
search(1, 1)
Should work just fine, but you should probably make the function have a variable 'object' so rather than this hardcoded example.

JavaScript TypeError with arrays and integers

So, I was having this problem with arrays in JavaScript.
I initialized some variables as shown here:
var world = new Array;
var monsters = new Array;
var items = new Array;
var x = 0;
var y = 0;
and tried to run this code on it:
while (y <= 49) { //generate world
world[x][y] = parseInt(Math.floor(Math.random()*2)); //0 = flatland, 1 = desert, 2 = mountain, 3 = swamp
x++;
if (x >= 49) {
x = 0;
y++;
}
}
x = 0;
y = 0;
but I get presented with this error:
"TypeError: can't convert undefined to object"
on the Math.random() line.
I've tried everything I can think of, but it still throws that error.
Any help will be greatly appreciated!
world[x][y] is not initialized. That's the problem. You need to intialize below the while statement
while (y <= 49) {
world[x] = new Array(); //add this
world[x] is not an array so you get an error when trying to assign a value to world[x][y], your method of filling the array seems strange to me, I'd do it this way
world = [];
for (x = 0; x <= 49; x++) { //generate world
world[x] = [];
for (y = 0; y <= 49; y++){
world[x][y] = parseInt(Math.floor(Math.random()*2)); //0 = flatland, 1 = desert, 2 = mountain, 3 = swamp
}
}
x = 0;
y = 0;
You are missing the (). World must be defined as a two dimensional array world[x] = new Array(); Using the [] notation is more convenient.

Categories

Resources