Passing objects to functions can be tricky, JavaScript passes objects sort of by reference that means when you change the object in the function it'll be changed after the function is done:
function sortmyarray(arr){
arr.sort();
}
function test(){
var arr=[3,2,1];
sortmyarray(arr);
console.log(arr);//[1,2,3]
}
test();
This only works when you invoke a function that changes the object, assigning a new value would not work:
function sortmyarray(arr){
arr=[1,2,3];
}
function test(){
var arr=[3,2,1];
sortmyarray(arr);
console.log(arr);//[3,2,1]
}
test();
But you can re assign a value to arr in test by a value returned from sortmyarray
function sortmyarray(arr){
return "hello world";
}
function test(){
var arr=[3,2,1];
arr=sortmyarray(arr);
console.log(arr);//"hello world"
}
test();
As to why passing objects to a function; it is so you can re use code here is a sort function that is re used:
var myObj={
toString:function(){
var ret=[];i=0;
for(i=0;i<this.arr.length;i++){
ret.push(this.arr[i].col1);
ret.push("\t");
ret.push(this.arr[i].col2);
ret.push("\n");
}
return ret.join("");
},
arr:[
{col1:99,col2:1},
{col1:1,col2:3},
{col1:3,col2:1},
{col1:1,col2:99}
]
}
function sortmyarray(arr, byColNames){
var len=byColNames.length;
arr.sort(function(a,b){
var i=0;
while(a[byColNames[i]]===b[byColNames[i]]
&& i<len){
i++;
}
if(i===len){
return 0;
}
return(a[byColNames[i]]>b[byColNames[i]])?1:-1;
});
}
sortmyarray(myObj.arr,["col2"])
console.log(myObj.toString());
sortmyarray(myObj.arr,["col2","col1"]);
console.log(myObj.toString());
sortmyarray(myObj.arr,["col1","col2"]);
console.log(myObj.toString());