Converte un array intero in un array di stringhe in JavaScript


88

Ho un array come di seguito:

var sphValues = [1, 2, 3, 4, 5];

quindi ho bisogno di convertire l'array sopra come quello sotto:

var sphValues = ['1', '2', '3', '4', '5'];

Come posso convertire? L'ho usato per il completamento automatico.


27
sphValues.map(String)
elclanrs

6
@elclanrs Dovresti pubblicarlo come risposta e non come commento
Mr. Alien,

7
[1,2,3,4,5].toString().split(",")
Mr_Green

1
@SonalPM Dovresti fare riferimento al markdown perché hai difficoltà a pubblicare un commento con un link, perché hai pubblicato e cancellato il tuo commento 4 volte, ora 5
Mr. Alien

Risposte:


201

Puoi usare map e passare il costruttore String come funzione, che trasformerà ogni numero in una stringa:

sphValues.map(String) //=> ['1','2','3','4','5']

Questo non muterà sphValues. Restituirà un nuovo array.


6
Non capisco perché questo non è stato accettato come risposta
MarsOne

3
Per i browser meno recenti che non supportano Array.map, puoi utilizzare underscore.js: _.map (sphValues, String)
Jonas Anseeuw

Sfortunatamente, questo convertirà anche i booleani in stringhe.
Dev

10

Usa Array.map:

var arr = [1,2,3,4,5];
var strArr = arr.map(function(e){return e.toString()});
console.log(strArr); //["1", "2", "3", "4", "5"] 

Modifica:
meglio usare arr.map(String);come @elclanrs menzionato nei commenti.


10

semplicemente usando metodi array

var sphValues = [1,2,3,4,5];   // [1,2,3,4,5] 
sphValues.join().split(',')    // ["1", "2", "3", "4", "5"]

6
for(var i = 0; i < sphValues.length; i += 1){
    sphValues[i] = '' + sphValues[i];
}

6

Usa .map()in questo contesto che è una mossa migliore, così come puoi fare come il codice seguente questo aggiungerebbe più leggibilità al tuo codice,

sphValues.map(convertAsString);

function convertAsString(val) {
  return val.toString();
}

3
 var value;
 for (var i = 0; i < data3.sph.length; i++) {
     value = data3.sph[i];
     //sphValues[i] = data3.sph[i];
     var obj = {
         label: value
     };
     sphValues.push(obj);
 }

È possibile utilizzare questo metodo per il completamento automatico. Penso che il tuo problema sarà risolto, ma non si convertirà come desideri, convertirà come

["label": "val1", "label": "val2"]

2

puoi semplicemente aggiungere un "" per convertirlo in un tipo di stringa.

var sphValues = [1,2,3,4,5];
for(var itr = 0; itr<sphValues.length;itr++){
  sphValues[itr] = '' + sphValues[itr];
}

1

Soluzione ES6

const nums = [1, 2, 3, 4, 5];
const strs = Array.from(nums.join(``));
console.log(strs);

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.