user3179249 user3179249 - 4 months ago 11
Javascript Question

Javascript array argument doesn't work

I had a javascript code to generate values for a table in HTML after sorting the values. At first I manually entered the array of values at the start of the javascript code. It was like: names=[tom,jerry,mickey,mouse]; grades=[10,20,30,40]; then sort them and write values in table. It worked perfect.

grades=[10,20,30,40];
var swapped;
do {
swapped = false;
for (var i=0; i < grades.length-1; i++) {
if (grades[i] > grades[i+1]) {
var temp = grades[i];
grades[i] = grades[i+1];
grades[i+1] = temp;
swapped = true;
}
}
} while (swapped);
for(j=0;j<grades.length-1;j++)
myTable.rows[j].cells[1].innerHTML = grades[i-1];
}


But now I have to convert it to a function. I tried like this:

function table(names,grades){
var swapped;
do {
swapped = false;
for (var i=0; i < grades.length-1; i++) {
if (grades[i] > grades[i+1]) {
var temp = grades[i];
grades[i] = grades[i+1];
grades[i+1] = temp;
swapped = true;
}
}
} while (swapped);
for(j=0;j<grades.length-1;j++)
myTable.rows[j].cells[1].innerHTML = grades[i-1];
}


But it does not work. I tried calling it like:

table([tom,jerry,mickey,mouse],[10,20,30,40]);


But it doesn't work. The table is empty. What is the problem?

Thanks.

Answer

Table is empty. What is the problem?

We don't know, especially as you just said "that part was working good".

The problem is that even after calling the function like this, arrays dont have the same value as before.

Sure, you have swapped the values in them :-) If you do not want to modify the originally passed arrays, you will have to copy them before. You can use the slice method for this:

function table(names,grades,table){
    var swapped;
    names = names.slice();
    grades = grades.slice();
    do {
        swapped = false;
        for (var i=0; i < grades.length-1; i++) {
            if (grades[i] > grades[i+1]) {
                var temp = grades[i];
                grades[i] = grades[i+1];
                grades[i+1] = temp;
                swapped = true;
            }
        }
    } while (swapped);
    for (var j=0; j<grades.length; j++)
//       ^^^                     ^^
        table.rows[j].cells[1].innerHTML = grades[j];
//                                               ^^^
}

table(["tom","jerry","mickey","mouse"], [10,20,30,40], myTable);

Notice I also fixed the output-loop and made table an extra parameter.