1

This is my function code here I want to return a 2d array in "a" variable;

var a = [[]];
var b = [[]];
var j = 0;
var i = 0;
let is = 2;
let desiredFields = ['display_name', 'phone'];

function myFunction() {
  console.log('Loading contacts...');
  let timer = new Date().getTime();
  Contacts.getContactsWorker(desiredFields).then((result) => {

    console.log(`Loading contacts completed in ${(new Date().getTime() - timer)} ms.`);
    console.log(`Found ${result.length} contacts.`);
    deger = result.length;
    a = new Array(result.length);
    for (i = 0; i < result.length; i++) {

      for (j = 0; j < 2; j++) {
        if (j == 0) a[i][j] = result[i].display_name;
        if (j == 1) a[i][j] = result[i].phone[0].number;
      }
    }

  });
  return a;
}

This is the code to call the function;

getItems(): Array <IDataItem> {
  b = myFunction();
  while (is <= 5) {
    this.items.push({
      id: is,
      name: b[0][0],
      description: b[0][1]
    });
    is = is + 1;
  }
  return this.items;
}

if my code is not correct ? how do I send a 2d array to a function ?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • What is the problem with this code? – VLAZ Sep 19 '19 at 06:48
  • JS: Loading contacts... JS: Loading contacts completed in 1429 ms. JS: Found 2 contacts. JS: ERROR Error: Uncaught (in promise): TypeError: Cannot set property '0' of undefined JS: TypeError: Cannot set property '0' of undefined – Enes Öztürk Sep 19 '19 at 06:48
  • this is my error. – Enes Öztürk Sep 19 '19 at 06:49
  • 1
    `a = new Array(result.length);` will create a new empty one dimensional array. In the following loop, you use `a[i][j]` where `a[j]` resolves as `undefined`. You need to initialise `a[i] = []` before trying to use the second dimensional array. – VLAZ Sep 19 '19 at 06:55
  • Also if `Contact.getContactsWorker().then` is asynchronous, then your function will always return the wrong value - see [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – VLAZ Sep 19 '19 at 06:58
  • thx for help I didn't see `a = new Array(result.length);` – Enes Öztürk Sep 19 '19 at 07:07

0 Answers0