During some basic tests of JS usage I have been playing around with object generation / addition to an array. I have so far used two different approaches for this problem:
- A single global object which has fields varied and then added.
- A factory function which generates the same object with an additional operation to show a slight difference (Addition of 1 to the value field)
While there are no errors at run time the value field on the global object property always outputs a 2 (Where the value is suppose to increment with the loop), while the function approach seemingly works without issue. Do you have any idea why this would be the case?
The final output I generated was "[{"name":"Hello","value":2},{"name":"Hello World","value":1},{"name":"Hello","value":2},{"name":"Hello World","value":2},{"name":"Hello","value":2},{"name":"Hello World","value":3}]" (from the console.log(JSON.stringify(testArray));).
I had expected an output of "[{"name":"Hello","value":0},{"name":"Hello World","value":1},{"name":"Hello","value":1},{"name":"Hello World","value":2},{"name":"Hello","value":2},{"name":"Hello World","value":3}]"
The code for the relevant functions and object can be found below.
Defining the global variable:
var globalVariable =
{
name: undefined,
value: undefined
}
Factory function:
function globalVariableGen(name, valueInput)
{
return output =
{
name: name,
value: valueInput + 1
}
}
Array generation function:
function test2()
{
var i, testArray = [];
for (i = 0; i < 3; i++)
{
alert(i.toString());
globalVariable.name = "Hello";
globalVariable.value = i;
testArray.push(globalVariable);
testArray.push(globalVariableGen("Hello World", i));
}
console.log(JSON.stringify(testArray));
}
Kind regards, Shadow