Javascript global variable getting set to a new value [duplicate] - javascript

This question already has answers here:
Change the value of an array changes original array JavaScript
(3 answers)
Closed 7 years ago.
I'm new to javascript and coding in general, and I could use some help.
I am setting a global variable (generatedNumbers) equal to another variable (numbers) so that I can do some validation on the array. However, when I change the value of numbers, my global variable generatedNumbers gets changed as well. Any help would be appreciated.
var generatedNumbers;
function generateNumbers(numberOfNumbers) {
'use strict';
var i;
generatedNumbers = [];
for (i = 0; i < numberOfNumbers; i = i + 1) {
generatedNumbers.push(generateRandomNumber(9).toString());
}
}
function checkEachValidNumberUsed(userExpression, numbers) {
'use strict';
var i, j;
for (i = 0; i < userExpression.length; i = i + 1) {
for (j = 0; j < numbers.length; j = j + 1) {
if (userExpression[i] === numbers[j]) {
numbers.splice(j, 1);
window.console.log(generatedNumbers);
}
}
}
if (numbers.length !== 0) {
return true;
}
}
function validateExpression(userExpression) {
'use strict';
var numbers, validUserInput;
numbers = generatedNumbers;
window.console.log(generatedNumbers);
if (checkEachValidNumberUsed(userExpression, numbers)) {
document.getElementById("feedbackText").innerHTML = "Each number must be used exactly once.";
} else {
return true;
}

Arrays (and all other non-primitive types) are pass-by-reference, not copied, when you use the assignment operator = or pass them to a function, so any changes made to numbers (or the values of the elements of numbers) will be reflected in generatedNumbers.
For your array here, numbers = generatedNumbers.slice(0); will sufficiently clone the array, but keep in mind that if the contents of the array is not a primitive type (e.g. any object that you use the new keyword to create) will not be cloned: both arrays will reference the same objects.

That's because they both refer to the same object. If you want to make a copy of generatedNumbers (which I think you want to do in validateExpression) use slice.
numbers = generatedNumbers.slice(0);

In Javascript if you have an array
var a = [1,2,3,4];
and assign a to another variable
var b = a;
the two are referring the very same array object... for example after
b.push(99);
a will also see the mutated array.
If you want to make a copy you need to do so explicitly for example with
var b = a.slice();

Related

for-loop not modifying a global variable? [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 6 years ago.
I wrote a for-loop that for some reason refuses to modify a global variable. Instead, it seems to create a local variable that it modifies temporarily. A condensed version of my code is as follows.
var clubsArray = [obj, obj, obj];
//each obj contains a property of "goalsFor" which holds an integer
var madridTotalGoals = 0;
var barcaTotalGoals = 0;
function findTotalGoals(clubsArray, totalGoals) {
for(var i = 0; i < clubsArray.length; i++) {
totalGoals += clubsArray[i].goalsFor;
}
}
findTotalGoals(clubsArray, barcaTotalGoals);
// this loops properly and does the math, but it never changes the value of barcaTotalGoals
In the full code there are numerous arrays that hold "club" objects; each contain a property key "goalsFor", which hold an integer as a value. There are also numerous "totalGoals" variables (two are specified here) that have been declared globally.
Does anyone know why the global variable (e.g. barcaTotalGoals) is not being modified when passed through this function? When I console log each step of this loop, the math is taking place but the result is not being stored. I apologize if this has been asked before but I've searched thoroughly.
The variable you are trying to pass, is passed by value and not reference. So it wont affect the original variable
You can assign the value once the for loop is finished
function findTotalGoals(clubsArray, totalGoals) {
for(var i = 0; i < clubsArray.length; i++) {
totalGoals += clubsArray[i].goalsFor;
}
barcaTotalGoals = totalGoals;
}
You are passing by value instead of by reference...
Instead, you could try like this:
clubsArray = [obj, obj, obj];
var totalGoals = {
madrid: 0,
barca: 0
}
function goalsByCountry(clubsArray, totalGoalsClub) {
for(var i = 0; i < clubsArray.length; i++) {
totalGoals[totalGoalsClub] += clubsArray[i].goalsFor;
}
}
goalsByTeam(clubsArray, 'barca');

Var Declarations in Javascript

I don't understand var a = [], i here. How can a be declared as both an array and whatever i's type is?
// Source: Javascript: The Good Parts, p. 63
Array.dim = function (dimension, initial) {
var a = [], i;
for(i = 0; i< dimension; i +=1)
{
a[i] = initial;
}
return a;
}
it means declare both (separately) - not declare them to be equal
same thing as:
var a = [];
var i;
The following code:
var a = [], i;
is EXACTLY the same as this code:
var a = [];
var i;
It means:
a is an empty array
i is an uninitialized var
Javascript variables don't have types.
a is initialized to an array; i is not initialized at all.
Nothing prevents you from later writing
a = 42;
i = ["Hi", "there!"];
Javavscript variables does not have any types. Here a is initialized as an array
var a = []; //Same as var a= new Array();
and i can have any value
var i = 0;// Here it is an integer
i = "Hello";// String. Type changed to string. But it is not a good practice
Read JavaScript Variables and DataTypes
var a = [], i literally means define a as an array and define i as a variable. Nothing is actually assigned to i.
For example:
var a = 5,
b = 8,
c = "string";
This basically allows you to define 3 variables without having to use the word var 3 times. Shorthand JavaScript.
Defining your variables before you use them prevent errors if the variable is not present, making functions more reliable. For example, not defining x as a variable will result in:
if(x) { /* native code */ }
Throwing an error but:
if(window.x) { /* native code */ }
Will not, because it checks the window object for x, where all global variables are stored.

Can I create dynamic object names in JavaScript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
javascript - dynamic variables
Dynamic Javascript variable names
I need to create a number of objects on a page and want to name them sequentially. Is there a way to do this in JavaScript?
for (i=0;i<num;i++){
var obj+i = new myObject("param1","param2");
obj+i.someProperty = value;
}
This way I can dynamically create a varying number of objects (dependent on the value "num") and then set their properties appropriately.
I can do this in PHP, is there a way to do it in JavaScript?
This isn't recommended, but does what you're trying to do (if you're running in a browser and not some other js environment).
for (i = 0; i < num; i++) {
window['obj' + i] = new myObject("param1","param2");
window['obj' + i].someProperty = value;
}
obj0.someProperty;
This works because global variables are actually properties of the window object (if you're running in the browser). You can access properties of an object using either dot notation (myObject.prop) or bracket notation (myObject['prop']). By assigning window['obj' + i], you're creating a global variable named 'obj' + i.
The better option is to use an array or parent object to store your objects.
myObjs = {};
for (i = 0; i < num; i++) {
myObjs['obj' + i] = new myObject("param1","param2");
myObjs['obj' + i].someProperty = value;
}
myObjs.obj0.someProperty;
Or use an array like lots of other answers suggest.
That's what arrays are for, to hold a collection of something:
var objs = [];
for (i=0;i<num;i++){
objs[i] = new myObject("param1","param2");
objs[i].someProperty = value;
}
Dynamic variables are almost always a bad idea.
You can create, and you can set/modify properties of that object.
Modified code:
var obj = {}; //
for (i=0;i<num;i++){
obj[i] = new myObject("param1","param2");
obj[i].someProperty = value;
}
I recommend you to use array. as
var obj = []; //
for (i=0;i<num;i++){
obj[i] = new myObject("param1","param2");
obj[i].someProperty = value;
}

Javascript: sort multidimensional array

After creating a multi-dim array like this, how do I sort it?
Assuming 'markers' is already defined:
var location = [];
for (var i = 0; i < markers.length; i++) {
location[i] = {};
location[i]["distance"] = "5";
location[i]["name"] = "foo";
location[i]["detail"] = "something";
}
For the above example, I need to sort it by 'distance'.
I've seen other questions on sorting arrays and multi-dim arrays, but none seem to work for this.
location.sort(function(a,b) {
// assuming distance is always a valid integer
return parseInt(a.distance,10) - parseInt(b.distance,10);
});
javascript's array.sort method has an optional parameter, which is a function reference for a custom compare. the return values are >0 meaning b first, 0 meaning a and b are equal, and <0 meaning a first.
Have you tried this?
location.sort(function(a,b) {
return a.distance - b.distance;
});
Both sort functions posted so far should work, but your main problem is going to be using location as a variable as it is already system defined.

javascript: speedy Array.contains(otherArray)?

I have an array of arrays. The inner array is 16 slots, each with a number, 0..15. A simple permutation.
I want to check if any of the arrays contained in the outer array, have the same values as
a test array (a permutation of 16 values).
I can do this easily by something like so:
var containsArray = function (outer, inner) {
var len = inner.length;
for (var i=0; i<outer.length; i++) {
var n = outer[i];
var equal = true;
for (var x=0; x<len; x++) {
if (n[x] != inner[x]) {
equal = false;
break;
}
}
if (equal) return true;
}
return false;
}
But is there a faster way?
Can I assign each permutation an integral value - actually a 64-bit integer?
Each value in a slot is 0..15, meaning it can be represented in 4 bits. There are 16 slots, which implies 64 total bits of information.
In C# it would be easy to compute and store a hash of the inner array (or permutation) using this approach, using the Int64 type. Does Javascript have 64-bit integer math that will make this fast?
That's just about as fast as it gets, comparing arrays in javascript (as in other languages) is quite painful. I assume you can't get any speed benefits from comparing the lengths before doing the inner loop, as your arrays are of fixed size?
Only "optimizations" I can think of is simplifying the syntax, but it won't give you any speed benefits. You are already doing all you can by returning as early as possible.
Your suggestion of using 64-bit integers sounds interesting, but as javascript doesn't have a Int64 type (to my knowledge), that would require something more complicated and might actually be slower in actual use than your current method.
how about comparing the string values of myInnerArray.join('##') == myCompareArray.join('##'); (of course the latter join should be done once and stored in a variable, not for every iteration like that).
I don't know what the actual performance differences would be, but the code would be more terse. If you're doing the comparisons a lot of times, you could have these values saved away someplace, and the comparisons would probably be quicker at least the second time round.
The obvious problem here is that the comparison is prone to false positives, consider
var array1 = ["a", "b"];
var array2 = ["a##b"];
But if you can rely on your data well enough you might be able to disregard from that? Otherwise, if you always compare the join result and the lengths, this would not be an issue.
Are you really looking for a particular array instance within the outer array? That is, if inner is a match, would it share the same reference as the matched nested array? If so, you can skip the inner comparison loop, and simply do this:
var containsArray = function (outer, inner) {
var len = inner.length;
for (var i=0; i<outer.length; i++) {
if (outer[i] === inner) return true;
}
return false;
}
If you can't do this, you can still make some headway by not referencing the .length field on every loop iteration -- it's an expensive reference, because the length is recalculated each time it's referenced.
var containsArray = function (outer, inner) {
var innerLen = inner.length, outerLen = outer.length;
for (var i=0; i<outerLen; i++) {
var n = outer[i];
var equal = true;
for (var x=0; x<innerLen; x++) {
if (n[x] != inner[x]) {
equal = false;
}
}
if (equal) return true;
}
return false;
}
Also, I've seen claims that loops of this form are faster, though I haven't seen cases where it makes a measurable difference:
var i = 0;
while (i++ < outerLen) {
//...
}
EDIT: No, don't remove the equal variable; that was a bad idea on my part.
the only idea that comes to me is to push the loop into the implementation and trade some memory for (speculated, you'd have to test the assumption) speed gain, which also relies on non-portable Array.prototype.{toSource,map}:
var to_str = function (a) {
a.sort();
return a.toSource();
}
var containsString = function (outer, inner) {
var len = outer.length;
for (var i=0; i<len; ++i) {
if (outer[i] == inner)
return true;
}
return false;
}
var found = containsString(
outer.map(to_str)
, to_str(inner)
);
var containsArray = function (outer, inner) {
var innerLen = inner.length,
innerLast = inner.length-1,
outerLen = outer.length;
outerLoop: for (var i=0; i<outerLen; i++) {
var n = outer[i];
for (var x = 0; x < innerLen; x++) {
if (n[x] != inner[x]) {
continue outerLoop;
}
if (x == innerLast) return true;
}
}
return false;
}
Knuth–Morris–Pratt algorithm
Rumtime: O(n), n = size of the haystack
http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm

Categories