Come convertire una stringa separata da virgole in un array?

Ho una stringa separata da virgole che voglio convertire in un array, in modo da poterlo analizzare in loop.

C'è qualcosa di integrato per fare questo?

Per esempio ho questa stringa

var str = "January,February,March,April,May,June,July,August,September,October,November,December";

ora voglio dividerla per la virgola e poi memorizzarla in un array.

Soluzione
var array = string.split(',');

riferimento MDN, utile soprattutto per il comportamento forse inaspettato del parametro limit. (Suggerimento: "a,b,c".split(",", 2) viene fuori ["a", "b"], non ["a", "b,c"].)

Commentari (7)

Fate attenzione se mirate a numeri interi, come 1,2,3,4,5. Se intendete usare gli elementi del vostro array come interi e non come stringhe dopo aver diviso la stringa, considerate di convertirli in tali.

var str = "1,2,3,4,5,6";
var temp = new Array();
// this will return an array with strings "1", "2", etc.
temp = str.split(",");

aggiungendo un ciclo come questo

for (a in temp ) {
    temp[a] = parseInt(temp[a], 10); // Explicitly include base as per Álvaro's comment
}

restituirà un array contenente interi e non stringhe.

Commentari (9)

Il metodo split() è usato per dividere una stringa in un array di sottostringhe e restituisce il nuovo array.

var array = string.split(',');
Commentari (3)