3

In ColdFusion, I can do this

<cfscript>
  favorites = [{"broker_label":"spectra"}]; 

  for (afav in favorites)   {
    writedump(afav);
  }
</cfscript>

And I get each row in the array.

If I try this in Javascript

favorites = [{"broker_label":"spectra"}];   

for (var afav in favorites) {
  console.log(JSON.stringify(afav));
}

And all I get is 0, or to be exact. "\"0\""

What is going on?

rrk
  • 15,677
  • 4
  • 29
  • 45
James A Mohler
  • 11,060
  • 15
  • 46
  • 72

2 Answers2

6

If you want to iterator over the values of an array you can use for…of or array.forEach()

favorites = [{"broker_label":"spectra"}]; 

for (let fav of favorites)   {
            console.log(JSON.stringify(fav));
}

// or:

favorites.forEach(elem => console.log(JSON.stringify(elem)))

for…in iterates over the properties which in the case of arrays is the indexes. Note that using for…in with arrays is discouraged when order is important:

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in:

Note: for...in should not be used to iterate over an Array where the index order is important.

James A Mohler
  • 11,060
  • 15
  • 46
  • 72
Mark
  • 90,562
  • 7
  • 108
  • 148
0

ColdFusion returns each element in the array.

Javascript return the index of the element in the array. To get similar results, I had to

 for (var afav in favorites)    {
            console.log(JSON.stringify(favorites[afav]));
 }
James A Mohler
  • 11,060
  • 15
  • 46
  • 72