Home > OS >  Why the output of this is number instead of items in array?
Why the output of this is number instead of items in array?

Time:11-28

My intention is is to get an array of arrays. i.e [['item','C']]. I'm unable to figure out why the below code always produces [2] ? Could someone please help?

function arrayOfArrays() 
{
 return [].concat([].push('item','C'))
}

console.log(arrayOfArrays());
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

console.log(arrayOfArrays());

CodePudding user response:

Array#push returns:

The new length property of the object upon which the method was called.

Whereas, Array#concat returns:

A new Array instance.

Try this instead:

console.log( [[].concat('item','C')] );
// OR
console.log( [ ['item','C'] ] );
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related