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

时间:2019-11-19 16:32:22

标签: javascript

我的代码需要多个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; 
}

但是由于有多个else语句,所以这行不通,我想知道是否有办法做到这一点?我还尝试将数据放入数组或对象中以进行迭代,但这也不起作用。

请帮助! :)

5 个答案:

答案 0 :(得分:1)

如果返回,则将从第一个立即返回,因此将所有结果存储在对象或数组中,并如下所示返回

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;

答案 1 :(得分:0)

您必须删除return / if块中的else-使用return会立即退出该函数。现在的代码方式,基本上是在缩短功能(这不是您要尝试的功能):

使用如下所示的变量来重组代码可能更有意义:

//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'));

答案 2 :(得分:0)

我不清楚您要问什么,但我想您想使用“ 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; 
}

答案 3 :(得分:0)

您可以执行以下操作:

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;

就像汤姆·奥(Tom O.)所说,return将立即退出您的功能。您可以使用数组以外的任何东西,但是请记住return仅执行一次。

答案 4 :(得分:0)

无论采用哪种方法,似乎都想构建某种类型的“集合”(数组,对象,集合,映射等),然后在最后将其返回。

但是,编码方式取决于函数存在的原因 。让我们看一个例子...

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

...此逻辑仅用于确保为first使用“默认”值-类似于null object pattern。对于此用例,我可能会建议采用空值合并以使其简单(或将来可能容易替换的东西):

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

仅看您的示例,似乎您可能只是想为多个变量获取像这样的默认值。对于该用例,您(或其他遇到此问题的人)可能想要一个与下面的代码段类似的功能。为此,使用对象和/或数组会很方便,因为如果需要的话,它们也可以是easily broken back out into multiple variables

首先,使用数组的示例函数:

// 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)
)

接下来,使用对象的示例:

// 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 })
)