0

Little weird behaviour in my javascript. I want to make a document.ready cleaner by using functions that return manipulated arrays.

function manipulateArray(arrayToBeManipulated){
  var result=new Array();
  //...push something in result....
  result.push(arrayToBeManipulated[0]);
  console.log(result);
  return result;
}

The console.log always shows me the correct result. But when I invoke the method

//...code...//
var x=new Array();
//push something into x
var result=manipulateArray(x);
console.log(result);

It always shows me undefined. Is there a reason for this?

EDIT maybe I forgot to tell that the function is called inside a $.ajax request. Could this be the problem?

riciloma
  • 1,456
  • 2
  • 16
  • 31

2 Answers2

3

The result of that is not undefined it is [undefined].

  1. You create array X with nothing in it.
  2. You create array Y with nothing in it.
  3. You push the 0 index of array X (which is implicitly undefined) into Y
  4. You return Y (which now has an explicit value of undefined for index 0.
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I skipped the part where I actually manipulate the array to see if there was anything wrong with the `return` itself – riciloma Jun 02 '15 at 09:29
  • @RiccardoLomazzi — You need to provide a test case that actually reproduces your problem. – Quentin Jun 02 '15 at 09:39
2

That is because your new Array x is empty, push something into it because when you are manipulating the array in the function, you took the first index which is [undefined] for your problem,

I have pushed single element and it works now

function manipulateArray(arrayToBeManipulated){
  var result=new Array();
  //...push something in result....
  result.push(arrayToBeManipulated[0]);
  console.log(result);
  return result;
}


//...code...//
var x=new Array();
x.push(1);
var result=manipulateArray(x);
console.log(result);
Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47