简体   繁体   English

多个 If Else 语句,只运行第一个

[英]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:我的代码需要多个 If Else 语句,但我不确定如何格式化它以便每个运行:

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?但这不起作用,因为有多个 else 语句,我想知道是否有办法做到这一点? 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 return 将立即从 first if 返回,因此将所有结果存储在 object 或数组中并返回如下

 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.您必须删除if / else块中的return - 使用return将立即退出 function 遇到的任何地方。 The way your code is now, you are basically short-circuiting the function (which is not what you're trying to do):你的代码现在的方式,你基本上是短路 function (这不是你想要做的):

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我不完全清楚你在问什么,但我认为你想使用“else if”语句: 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.就像 Tom O. 所说的return将立即退出您的 function。 You can use something other than an array but remember return is executed only once.你可以使用数组以外的东西,但记住return只执行一次。

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 .无论您采用哪种方法,您似乎都想构建某种“集合”(数组、object、集合、map 等),然后在最后返回它

But, the way you code it depends on the reason your function exists .但是,您编码的方式取决于您的 function 存在的原因 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 . ...此逻辑的存在仅是为了确保first使用“默认”值 - 类似于null object 模式 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.对于该用例,您(或遇到此问题的其他人)可能需要类似于以下代码片段中的 function。 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.使用对象和/或 arrays 可以很方便,因为如果您愿意,它们也可以很容易地分解为多个变量

First, example functions using arrays:首先,使用 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 }) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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