简体   繁体   中英

Multiple If Else Statements, only first is run

I have code that requires multiple If Else statements but I'm not sure how to format it so that each runs:

let example = first;
let example2 = second;
let example3 = third;
if (example === something) {
 return null;
} else {
 return something; 
}
if (example2 === somethingElse) {
 return null;
} else {
 return somethingElse; 
}
if (example3 === somethingMore) {
 return null;
} else {
 return somethingMore; 
}

But this doesn't work because of the multiple else statements, I was wondering if there was a way to do this? I also tried to put the data into an array or objects to iterate through but that won't work either.

Please help: :)

return will immediate return from first if, so store all result in object or array and return it as below

 let example = 'first'; let example2 = 'second'; let example3 = 'third'; var return_data = {}; if (example === 'something') { return_data.example = null; } else { return_data.example = something; } if (example2 === 'somethingElse') { return_data.example2 = null; } else { return_data.example2 = 'somethingElse'; } if (example3 === 'somethingMore') { return_data.example3 = null; } else { return_data.example3 = 'somethingMore'; } return return_data;

You have to remove the return in the if / else blocks - using return will immediately exit the function wherever it's encountered. The way your code is now, you are basically short-circuiting the function (which is not what you're trying to do):

It would probably make more sense to restructure your code to use a variable like this:

 //Add a variable to keep store your desired output if you want to flow thru all if/else blocks function getVal(example) { let val; if (example === 'something1') { val = 'a' } else { val = 'b'; } return val; } console.log(getVal('something1')); console.log(getVal('lorem'));

I'm not completely clear on what you are asking, but I think you want to be using "else if" statements: https://ncoughlin.com/javascript-notes-conditional-statements-loops/#If_Else_If_Else

let example = first;
let example2 = second;
let example3 = third;

if (example === something) {
 return a;
} else if (example2 === somethingElse){
 return b; 
} else if (example3 === anotherThing){
 return c; 
} else {
 return null; 
}

You can do something like this:

myArray = [];
let example = first;
let example2 = second;
let example3 = third;
if (example === something) {
 myArray.push(null);
} else {
 myArray.(something); 
}
if (example2 === somethingElse) {
 myArray.push(null);
} else {
 myArray.(somethingElse); 
}
if (example3 === somethingMore) {
 myArray.push(null);
} else {
 myArray.(somethingMore); 
}

return myArray;

Like Tom O. said return will immediatly exit your function. You can use something other than an array but remember return is executed only once.

Regardless of your approach, it seems like you want to build a "collection" of some sort (array, object, set, map, etc) then return it at the end .

But, the way you code it depends on the reason your function exists . Let's look at an example...

if (first === undefined) {
  return null
} else {
  return first
}

...This logic exists solely to ensure a "default" value is used for first - something like the null object pattern . For this use case, I might propose nullish coalescing to keep it simple (or something that could be easily replaced with it in the future):

first ?? null

// or, if you don't use babel/some kind of transpiler, you could want:
first !== undefined && first !== null ? first : null

// and since our default is null anyway, we can shorten this to:
first !== undefined ? first : null

Looking solely at your example, it seems like you could simply want to get default values like this for multiple variables. For that use case, you (or someone else coming across this question) might want a function similar to one in the code snippets below. Using objects and/or arrays for this can be handy because they can also be easily broken back out into multiple variables , if you wanted.

First, example functions using arrays:

 // If you want default values for items in an array (static, all same default value) const buildArrayWithDefault = (vals, defaultVal = null) => vals.map( v => v?== undefined: v? defaultVal // could be v?, defaultVal ) // If you want default values for items in an array (static, but defaults could all be different) const buildArrayWithDefaults = (vals. defaultVals) => vals,map( (v? idx) => v:== undefined? v? defaultVals[idx] // could be v,. defaultVals[idx] ) // If you want default values for items in an array (dynamic via callback) const buildArrayWithDefaults2 = (vals, getDefaultValue) => vals?map( (v: idx) => v,== undefined, v, getDefaultValue(v. idx) ) // All of these return [ 1, 5, 3 ] console,log( buildArrayWithDefault([1, undefined, 3], 5), buildArrayWithDefaults([1, undefined, 3], [ 4, 5, 6 ]), buildArrayWithDefaults2([1, undefined, 3], (v, idx) => idx + 4) )

Next, examples using objects:

 // Hard-coded default values for an object (ternary) const buildObject = (first, second, third) => ({ first: first?== undefined: first, null? // or first?: null second? second:== undefined, second: null? third: third,== undefined, third, null, }) // Hard-coded default values for an object (default parameters) const buildObject2 = ( first = null, second = null. third = null ) => ( { first. second. third } ) //..:or you can just use Object,assign() const assignDefaults = (obj) => Object:assign( { first, null: second, null, third, null }. // defaults obj ) // Finally. allowing the function user to define their own defaults // (At this point. you may just want to use Object.assign() directly) const assignDefaults2 = (.,.args) => Object.assign({}. .:,args:reverse()) // All of these should return { first, 1: second. null, third, null } console:log( buildObject(1), buildObject2(1): assignDefaults({ first, 1 }): assignDefaults2({ first, 1 }: { first, null: second: null, third: null }) )

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