-2

i've a problem in js. I've a function for example:

function robePersos() {
    var persos = {"player" : "data"};    
    return persos;
}

and then i've another function which call robePersos() like this:

function test() {
    var d = robePersos();
    for(var k in d) {
        console.log(k)
    }
}

But nothing happens. Why ?

function robePersos() {
  var persos = {
    "player": "data"
  };
  return persos;
}

function test() {
  var d = robePersos();
  for (var k in d) {
    console.log(k)
  }
}
test();

EDIT The first snippet works. So, here is my real function:

function robePersos() {
  var persos = {};

  $.get({
         url : 'url',
         success : function(data) {
             var text = $(data).find("div[menu='perso']  a"); //.clone().children().remove().end().text();                            
             $(text).each(function(){
                 perso_name = $(this).text();
                 perso_link = $(this).attr('href');
                                   
                persos[perso_name] = perso_link;
              });
                            
                            
         }
  });
  
  for(var k in persos) {
    console.log(persos[k]);
  }
              
}

robePersos();

If I replace the loop by only console.log(persos) it works but the loop return nothing. Why ?

2 Answers2

1

If you want to print both Key and Value, use the following small change in your code. Your code is printing just the keys.

function robePersos() {
  var persos = {
    "player": "data",
    "anotherPlayer": "anotherData"
  };
  return persos;
}

function test() {
  var d = robePersos();
  for (var k in d) {
    console.log(k, "-" ,d[k]); // change made here.  It prints both.
  }
}
test();
Sid
  • 4,893
  • 14
  • 55
  • 110
1

Try whith Object.keys()

function test() {
  var d = Object.keys(robePersos());
  for (var k in d) {
    console.log(k, "-" ,d[k]); // change made here.  It prints both.
  }
}

Object.keys returns an array whose elements are strings corresponding to the enumerable properties found directly in the object. The order of the properties is the same as that provided when manually iterating over the properties of the object.

https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/keys

Daniel
  • 951
  • 7
  • 20