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
  • 76
  • 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
  • 88,177
  • 15
  • 123
  • 150
randomusername
  • 7,559
  • 20
  • 46
0
var z = "123456".split();

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

CollinD
  • 6,676
  • 2
  • 21
  • 42
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
  • 351,820
  • 24
  • 303
  • 358