-2

Noob to javascript and when i tried adding element to an array, the output was something like this:

var shit = ["r", "t", "y"]
shit.unshift("q");
shit;
Array(4) [ "q", "r", "t", "y" ]

Where is was looking for this:

var shit = ["r", "t", "y"]
shit.unshift("q");
shit;
[ "q", "r", "t", "y" ]
choke
  • 1
  • 3
    Sorry, what's the question? – Phix Feb 19 '19 at 02:40
  • The output is printing "array(4)" before the expected result. – choke Feb 19 '19 at 02:41
  • 1
    It would help if you would tell us where you are using this javascript. Not in a webpage, I guess, because on a webpage this doesn't output shit (pun intended). – Roemer Feb 19 '19 at 02:44
  • That's just how your console shows arrays (the output type is an array). If you convert it to a string, it would be displayed without that. That text in the output doesn't change the fact that it's the correct array though, and you can perform your expected operations on that. – nbrooks Feb 19 '19 at 02:44
  • oh no man, just messing around. Btw, its in blank page's console. – choke Feb 19 '19 at 02:45
  • Ah in the console. What would you care if it outputs that in the console? It is only for debugging purposes! Context matters a LOT if you want answers, so I am glad you cleared that up. – Roemer Feb 19 '19 at 02:46

2 Answers2

2

The Array(4) before the [...] in the console is just the console telling you that the object being logged is an array of length 4. It doesn't mean anything else; you're still free to manipulate the array as you want without problems - it's not like it's actually become a string or anything strange like that..

I suppose if you really wanted not to see the Array(..) before the items, you could use JSON.stringify when you log it:

var arr = ["r", "t", "y"]
console.log(JSON.stringify(arr));

(though, note that passing an object to console.log will show you the live object, whereas stringifying it will show you the object at the moment it was logged - see Weird behavior with objects & console.log )

Snow
  • 3,820
  • 3
  • 13
  • 39
0

If that code is inside a function, you can

return shit;

Or maybe if you want to print it in the console, you can

console.log(shit);

But if you are just executing that in the browser console, I think there is no way to obtain the result you are looking for.