Brixsta
Brixsta

Reputation: 627

Array only prints length instead of contents

My array is printing out the length instead of its contents. I genuinely looked for an answer but found none. Here is my code:

<p id="para">

</p>

var myArray = [1,2,3,4,5];

myArray = myArray.unshift('Charlie');

document.getElementById('para').innerHTML = myArray;

I want this array to print out Charlie,1,2,3,4,5 but instead it prints out 6. What dumb thing am I doing wrong here?

Upvotes: 0

Views: 180

Answers (2)

lhavCoder
lhavCoder

Reputation: 961

.unshift returns the length of the array. So what you had done in the above code equated myArray to myArray.unshift()'s return value. myArrays value became the length of the array which was 6

So all you have to code is

myArray.unshift('Charlie');

var myArray = [1,2,3,4,5];
//console.log(myArray);
myArray.unshift('Charlie');
document.getElementById('para').innerHTML = myArray;
<p id="para"></p>

A nicer way of presenting this would be

var myArray = [1,2,3,4,5];
//console.log(myArray);
myArray.unshift('Charlie');
var str='';
for(var i=0; i<myArray.length; i++)
{
str=str+myArray[i]+" ";
}
document.getElementById('para').innerHTML = str;
<p id="para">

</p>

Upvotes: 1

E. Sundin
E. Sundin

Reputation: 4181

Reading the docs for Array.unshift is says that it returns the length of the array.

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the new array.

You might just want to remove the assign operator like so

var myArray = [1, 2, 3, 4, 5];

myArray.unshift('Charlie');

document.getElementById('para').innerHTML = myArray.join(',');
<div id="para">

</div>

Upvotes: 3

Related Questions