0

How do I convert a string var a = "123456"; in to an array z = [1,2,3,4,5,6];? I tried everything and nothing seems to work. Thanks!

MrJgaspa
  • 86
  • 5
  • 2
    Did you try [`.split`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) and [`parseInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt)? – Mike Cluck Jan 11 '16 at 21:52

3 Answers3

0

Using split('') with Number works using JavaScript-C:

'123456789'.split('').map(Number)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
peak
  • 105,803
  • 17
  • 152
  • 177
randomusername
  • 7,927
  • 23
  • 50
0
var z = "123456".split();

See javascript docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

CollinD
  • 7,304
  • 2
  • 22
  • 45
0

Just use String.prototype.split and for casting to number the Number object with Array.prototype.map.

var array = '123456'.split('').map(Number);

document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392