array passed as parameter issue - javascript

I've got 2dim array set as global variable populated with numbers on row - 0 and strings on row-1.
But when I passed it as a parameter to a function most of its values modifies into undefined but in one strangely value is kept!?!
function formElements(howMany){
elArr = [];
var w; var surface;
for(var j=0; j<howMany; j++){
w = randomNumber(1,200);
surface = w*randomNumber(1,100);
elArr[0] =[j];
elArr[1] =[j];
elArr[0][j]=surface;
elArr[1][j]='_'+j;
}
aFunction(elArr,...other parameters....); //in this function I receive array with these undefined values I mentioned above!!!
}
function randomNumber(x,y) {
return Math.floor((Math.abs(y - x) + 1) * Math.random()) + Math.min(x, y);
}
Could somebody tell me what's wrong?
10x and BR

The references to j make it look like this is inside a loop. In which case, I don't think this is doing what you want:
elArry[0] = [j];
This sets the value of elArray[0] to an array with a single element, j. If you're doing that inside your loop then you're overwriting the arrays every time with a new one with a single element.
EDIT:
And now that you've posted the full loop that's verified. You probably want something like:
function formElements(howMany){
elArr = [[],[]];
for(var j=0; j<howMany; j++){
elArr[0][j]=surface;
elArr[1][j]='_'+j;
}
aFunction(elArr,...other parameters....);
}

Related

How to pass an array with a key to the argument of a function? (Working with multi-dimensional arrays)

This may not be a good question, but it does makes sense(atleast to me, it does.)
Suppose I have a multi-dimensional array called temporaryFrequency. Now, I want to write a function which will take one argument --> frequencyArray[number]. This will be more clear from the code:
JS:
function getMaxTemporaryFrequency(frequencyArray[number]){
var maxOutofThese = frequencyArray[number][0];
for(var i = 0; i < frequencyArray[number].length; i++){
if(frequencyArray[number][i] > maxOutofThese)
maxOutofThese = frequencyArray[number][i];
}
return maxOutofThese;
}
This is the function which will return the maximum frequency from a sub-array of an array. Now, I will execute the following code to call the function:
//This is to get the max out of the temporary frequencies
for(var n = 0; n < temporaryFrequency.length; n++){
var maximumTempFrequency + (n + 1) = getMaxTemporaryFrequency(temporaryFrequency[n]);
}
Now, I have one more question attached to this. Can variable names be concatenated, like a did here? For example, for each loop count, I want to make variables : maximumTempFrequency1 , maximumTempFrequency2 , maximumTempFrequency3 and so on.
Now, this call of the function passes the nth element of the temporaryFrequency array to the function, which should return the greatest value from that nth sub-array. But, that is not working.
So, to summarise my question:
1) Can we pass an array with a key to function, like I did here? If
no, is there any way to do it?
2) Can we concatenate strings to make a variable name, like I did in
the 'for' loop? If no, is there any other method
*NOTE: For this question, viewers don't need to know the contents of the temporaryFrequency array.
The straight answer to your two questions are No.
The syntax function getMaxTemporaryFrequency(frequencyArray[number]) { ... } is not valid. The parser is expecting an identifier for the parameter name, and identifiers can't have brackets in them [ or ]. This results in the error:
Uncaught SyntaxError: Unexpected token [
Similarly, your variable name is also syntactically invalid. var maximumTempFrequency + (n + 1) = //anything results in
Uncaught SyntaxError: Unexpected token +
To answer your follow up questions of How to make it work, for the first question you can pass the dereferenced array member to the function when you call it (instead of when you declare it).
var frequencyArray = []; // fill it with your values
var number = 0; // or whatever number you want
function getMaxTemporaryFrequency(arr){
var maxOutofThese = arr[0];
for(var i = 0; i < arr.length; i++){
if(arr[i] > maxOutofThese)
maxOutofThese = arr[i];
}
return maxOutofThese;
}
function getMaxTemporaryFrequency(frequencyArray[number]);
For the latter one, you want to store the results to an array, like this:
//This is to get the max out of the temporary frequencies
var maximumTempFrequency = [];
for(var n = 0; n < temporaryFrequency.length; n++){
maximumTempFrequency[n+1] = getMaxTemporaryFrequency(temporaryFrequency[n]);
}
Note that your syntax getMaxTemporaryFrequency(temporaryFrequency[n]) is an example of what I put in the first code block above.

How do I correctly split an array of strings of is it another issue?

I am trying to access a random element from an array of strings as per other examples here on SO. I am using Raphael.js and regions[j] below returns an array of Raphael objects - hence the .data(id). This seems to be ok, but theCountyNames, as outlined in the comment below returns all of the strings as one long string. I am guessing that this is why randCounty returns a single random letter, but when I try appending a comma in the loop (+",") and using split as per this question, I still get one random single letter. Perhaps I am implementing this incorrectly or maybe it is another issue? Thanks.
function pickRandCounty(){
var theCountyNames = new Array();
for (var j = 0; j < regions.length; j++) {
theCountyNames = regions[j].data('id');
document.write(theCountyNames);//THIS GIVES ME THE COMPLETE LIST OF ITEMS IN THE ARRAY BUT ALL AS ONE STRING
//document.write("<hr>");
}
//var randCounty = theCountyNames[Math.floor(Math.random() * theCountyNames.length)];
//document.write(randCounty);//THIS JUST RETURNS ONE RANDOM LETTER??
}
Using Array.prototype.push to append a new item to an Array.
function pickRandCounty(){
var theCountyNames = [],
j;
for (j = 0; j < regions.length; ++j) {
theCountyNames.push(regions[j].data('id'));
}
j = Math.floor(Math.random() * regions.length);
return theCountyNames[j];
}
However, this is not optimised as you can set the length of the Array in advance and you can even completely skip the loop,
function pickRandCounty(){
var j = Math.floor(Math.random() * regions.length);
return regions[j].data('id');
}
The error seems to be in this part of line.
theCountyNames = regions[j].data('id'); //wrong
theCountyNames.push(regions[j].data('id')); //right
Second mistake
document.write(theCountyNames); //it will keep on appending the string in the DOM
document.write("<br>" + theCountyNames);//right

recursive function with an array as input

I am trying to create a function that gets chest exercises from an array called chest.
This function needs to be able to pick several exercises at random, which I have done using a random pointer. To stop duplicate exercises I compare the chest exercise picked (i.e chest[pointer]) and compare it against all the values in the final array.
If the new exercise is not already in the final array, the newly picked exercise is returned and then pushed onto the final array. If it is already in the final array, the function is called recursively. The idea being that the function will run recursively until it finds a new exercise which has not already been chosen:
Get Chest:
function getChest(arr){
var pointer = 0;
//random array pointer
pointer = Math.round(Math.random() * (chest.length - 1));
//check for duplicate
for(var i = 0; i < arr.length - 1; i++){
if(arr[i].name === chest[pointer].name){
return getChest(arr);
} else {
return chest[pointer];
}
}
};
The main function uses this method to select exerises randomly. The final array is called 'day'.:
function chooseExercises(){
for(i = 0; i <= 5; i++){
ex = getChest(day);
day.push(ex);
}
}
The problem I am having is that there are still duplicates when I run it. Any idea as to what is going wrong? (I am using angularJS)
Modify your function to this,
function getChest(arr){
var pointer = 0;
//random array pointer
pointer = Math.round(Math.random() * (chest.length - 1));
//check for duplicate
for(var i = 0; i < arr.length; i++){
if(arr[i].name === chest[pointer].name){
return getChest(arr);
}
}
return chest[pointer];
};
Basically, the loop is breaking before the value is checked with its full length.
EDIT: also your loop is running over arr.length-1 times, which actually should be just arr.length.

Array reads, then stops- error: Cannot set property '0' of undefined

I'm trying to read in a csv string to a 2D array and for some reason it stops when it gets to the second iteration of the first loop.
Here's the Fiddle and the code:
$(document).ready(function(){
var lay = [[]];
document.getElementById("result").innerHTML = value;
bits = value.split(',');
console.log(bits.length);
elm = bits.length/4;
count=0;
console.log(bits[6]); //here it reads but won't assign to the array
for (i=0; i<=elm; i++)
{lay[i]=[];
console.log('i:'+i);
for (j=0; j<=4; j++)
{ console.log('j:' + j);
console.log('count:' + count);;
lay[i][j] == bits[count];
count = count + 1;
console.log('bit value:' + bits[count]);
}
}
console.log(lay[0][0]);
});
The value for the next element reads and displays, but when I try to assign the data to the array it errors out.
Fixed Code
added the redeclaration of the array in the first loop
That made the error go away.
Fiddle
Thanks!
Something wrong with u'r lay array I think.
Is this element set? lay[i][j]
I think I solved it
http://jsfiddle.net/hgm8r/3/
I've made two changes:
Declared the `lay' value outside the loop
var lay = Array();
And updated it at the start of the first loop
lay[i] = Array();
And now it runs without errors.

Random Array Repeats Index Items

This code works fine in their example but repeats some of my index items when I try and use it.
var lastloaded = 0;
window.onload = loadPages;
Array.prototype.knuthShuffle = function()
{
var i = this.length, j, temp;
while ( --i )
{
j = Math.floor( Math.random() * (i - 1) );
temp = this[i];
this[i] = this[j];
this[j] = temp;
}
};
var arr = ["aCard.html", "bCard.html", "cCard.html", "dCard.html"];
function loadPages () {
arr.knuthShuffle();
var frame = document.getElementById("frameWrap");
if (lastloaded+1>arr.length){
lastloaded = window.location = "greatJob.html";
}
frame.src = arr[lastloaded];
lastloaded++;
};
document.getElementById('tom').onclick = loadPages;
Can anyone tell me what I am missing from this code to keep it from repeating items in my array?
I'm not sure I completely understand how your page works, but it seems like it is shuffling the array in order to figure out the next page to go to. This means that it is newly shuffled with every page load, and you therefore have no guarantee as to the uniqueness of the pages - in fact, it would be extremely unlikely for you to get all the unique pages (1 in n!, to be precise)
In order to ensure uniqueness, you MUST save the generated order, not just the index you were at.
You have a problem with your declaration of j and temp which might add up on multiple shuffles and give you some strange behavior.
specifically this line:
var i = this.length, j, temp;
and these lines:
j = Math.floor( Math.random() * (i - 1) );
temp = this[i];
The problem here is that you didn't actually declare the j and temp variables, that's an invalid syntax. Then when declaring them within your loop without the var keyword they are treated as global variables. Solvable by modifying the first line into:
var j, temp;
var i = this.length;
Edit: Actually that isn't it, as already pointed out by t.niese every time you click tom you're re-shuffling.
What you want to do is shuffle once and use the newly shuffled array every time. So decouple your shuffling from your page loading by taking arr.knuthShuffle(); out of the loadPages() function.

Categories

Resources