2013-11-24 9 views
5

se avessi una stringa di testo, come potrei convertire quella stringa in una matrice di ciascuna delle singole parole nella stringa?premendo ogni parola su un array

qualcosa di simile:

var wordArray = []; 
var words = 'never forget to empty your vacuum bags'; 

for (//1) { 
wordArray.push(//2); 
} 

1 = passare attraverso ogni parola nelle parole stringa denominata 2 = spingono quella parola alla matrice

questo creerebbe il seguente array:

var wordArray = ['never','forget','to','empty','your','vacuum','bags']; 

risposta

13

Non iterare, basta usare split() che restituisce un array:

var words = 'never forget to empty your vacuum bags', 
    wordArray = words.split(' '); 

console.log(wordArray); // ["never", "forget", "to", "empty", "your", "vacuum", "bags"] 

JS Fiddle demo.

Riferimenti:

+2

Potrebbe voler gestire più spazi con '.split (/ \ s + /)'. – jfriend00

+0

non so perché ma la parolaArray mostra che è un oggetto ... non un array ... – munmunbb

+1

@Wendy: tutto in JavaScript è un oggetto, inclusi gli array. Se provi a eseguire 'console.log (instanceArray instanceof Array)' che * dovrebbe * risultare in 'true', a meno che non sia quello che hai già provato? Ma dal momento che 'String.prototype.split()' restituisce sempre una matrice (per quanto ne so, leggendo i documenti alcune volte), sono abbastanza fiducioso che si tratta di una matrice restituita. –

Problemi correlati