Perché la funzione mappa javascript restituisce undefined?


115

Il mio codice

 var arr = ['a','b',1];
 var results = arr.map(function(item){
                if(typeof item ==='string'){return item;}  
               });

Questo dà i seguenti risultati

["a","b",undefined]

Non voglio undefined nell'array dei risultati, come posso farlo?


3
Perché non restituisci nulla a meno che non sia una stringa. Pertanto, l'ultimo articolo ritorna undefined. Cosa ti aspetti di restituire se non è una stringa? Una stringa vuota?
BenM

2
@ BenM se non è una stringa non voglio che venga restituito nulla, nemmeno undefined.
Akshat Jiwan Sharma

4
Sembra che stavo usando il metodo sbagliato per farlo. Userò il filtro come suggerito.
Akshat Jiwan Sharma

Potresti voler accettare una risposta.
Ikke

3
jQuery.map è in realtà abbastanza intelligente da non includere valori non definiti e nulli nell'array risultante.
Donald Taylor

Risposte:


180

Non stai restituendo nulla nel caso in cui l'articolo non sia una stringa. In tal caso, la funzione restituisce undefined, ciò che stai vedendo nel risultato.

La funzione map viene utilizzata per mappare un valore su un altro, ma sembra che tu voglia effettivamente filtrare l'array, per il quale una funzione map non è adatta.

Quello che vuoi veramente è una funzione di filtro . Accetta una funzione che restituisce vero o falso a seconda che si desideri o meno l'elemento nell'array risultante.

var arr = ['a','b',1];
var results = arr.filter(function(item){
    return typeof item ==='string';  
});

2
Ahh ... non sapevo ci fosse una funzione di filtro, grazie.
Akshat Jiwan Sharma

Questo ha abbastanza senso. Non stavo facendo la mappatura, stavo filtrando ... Come lo sapevi ?! Oo grazie ^. ^
DigitalDesignDj

abbastanza logico Grazie @Ikke
Malik Khalil

Ho risparmiato i miei sforzi per cercare una risposta. Grazie.
Sophie Zhang

22

Il filtro funziona per questo caso specifico in cui gli elementi non vengono modificati. Ma in molti casi, quando si utilizza la mappa, si desidera apportare alcune modifiche agli elementi passati.

se questo è il tuo intento, puoi usare ridurre :

var arr = ['a','b',1];
var results = arr.reduce((results, item) => {
    if (typeof item === 'string') results.push(modify(item)) // modify is a fictitious function that would apply some change to the items in the array
    return results
}, [])

1
Grazie - maprisultati in array con undefined. filterrestituisce solo l'articolo o meno. questo è perfetto
Zach Smith

15

Poiché ES6 filtersupporta la notazione con freccia appuntita (come LINQ):

Quindi può essere ridotto a seguire una riga.

['a','b',1].filter(item => typeof item ==='string');

10

La mia soluzione sarebbe usare il filtro dopo la mappa.

Questo dovrebbe supportare ogni tipo di dati JS.

esempio:

const notUndefined = anyValue => typeof anyValue !== 'undefined'    
const noUndefinedList = someList
          .map(// mapping condition)
          .filter(notUndefined); // by doing this, 
                      //you can ensure what's returned is not undefined

8

Restituisci un valore solo se l'elemento corrente è un string . Forse l'assegnazione di una stringa vuota altrimenti sarà sufficiente:

var arr = ['a','b',1];
var results = arr.map(function(item){
    return (typeof item ==='string') ? item : '';  
});

Ovviamente, se vuoi filtrare qualsiasi elemento non stringa, non dovresti usare map(). Piuttosto, dovresti cercare di usare la filter()funzione.


3
Questo restituisce una stringa vuota se esiste un numero
Prasath K

5
var arr = ['a','b',1];
 var results = arr.filter(function(item){
                if(typeof item ==='string'){return item;}  
               });

3

Puoi implementare come una logica di seguito. Supponi di volere un array di valori.

let test = [ {name:'test',lastname:'kumar',age:30},
             {name:'test',lastname:'kumar',age:30},
             {name:'test3',lastname:'kumar',age:47},
             {name:'test',lastname:'kumar',age:28},
             {name:'test4',lastname:'kumar',age:30},
             {name:'test',lastname:'kumar',age:29}]

let result1 = test.map(element => 
              { 
                 if (element.age === 30) 
                 {
                    return element.lastname;
                 }
              }).filter(notUndefined => notUndefined !== undefined);

output : ['kumar','kumar','kumar']
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.