简体   繁体   中英

If Else and Javascript what am I missing?

I think there is an issue in my if else statement as I think it is giving me the opposite result of what I'm expecting.

console.log(_.map(item, function(n){return _.find(n).tertiary})) 
//is undefined.

console.log(_.map(item, function(n){return _.find(n).primary}));
//is ["green"]

I use the following if statement to assign a value to my variable:

if(_.map(item, function(n){return _.find(n).tertiary}) === undefined ){
   var audience = _.map(item, function(n){return _.find(n).tertiary});
   } else {
   var audience = _.map(item, function (n) {return _.find(n).primary});
   }

console.log(audience);//this is undefined

Am I doing something wrong or is this working correctly? I expect the answer to be ["green"].

Change your if else to:

if(_.map(item, function(n){return _.find(n).tertiary}) === undefined ){//since tertiary is undefined, so use primary instead
    var audience = _.map(item, function (n) {return _.find(n).primary});
} else {
    var audience = _.map(item, function(n){return _.find(n).tertiary});
}

Just for a little variety:

var colours = _.map(item, function(n){
    return {primary: _.find(n).primary, tertiary: _.find(n).tertiary}
})

var audience = colours.primary || colours.tertiary

console.log(audience)

Although underscore/lodash could probably lend a hand in getting those values out in a cleaner manner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM