May Sun
May Sun

Reputation: 99

nodejs returned unexpected strange output

console.log(a,b)

Below is the output of my above code

enter image description here

And when I run this

for(var i=0; i<a.length; i++){
   c[a[i]] = b[i];
}

But I got BLANK when I do console.log(c)

That's so strange, I do a fiddle my logic is fine : http://jsfiddle.net/8m97zk8d/

Upvotes: 1

Views: 43

Answers (2)

Tushar
Tushar

Reputation: 87203

c is declared as array and array should not have string as key, use object instead. Declare c as object.

Updated Fiddle

var a = ['Child', 'Adult'];
var b = [2, 6];
var c = {}; // Declare as empty Object

for (var i = 0; i < a.length; i++) {
  c[a[i]] = b[i];
}

console.log(c);
document.getElementById('result').innerHTML = JSON.stringify(c, 0, 4);
<pre id="result"></pre>

Upvotes: 2

slomek
slomek

Reputation: 5126

You have created an array c and assigned attributes to it. Check out that those attributes are available to log:

console.log(c.Child);
console.log(c.Adult);

If you want to access them in a traditional way, then redefine c as an object:

var a = [ 'Child' , 'Adult'];
var b = [2,6];
var c = {};

for(var i=0; i<a.length; i++){
                c[a[i]] = b[i]
            }
console.log(c);

Upvotes: 0

Related Questions