如何从if条件中获取多个值

时间:2019-07-02 13:03:07

标签: javascript arrays if-statement nested conditional-statements

我想从函数中为特定条件(在“ As_cm”值上)获取两个值,并对这些值执行一些操作。我做不到。

function steelSection() {
    if (As_cm <= 29.2) {
       return [D  = 152.4, B = 152.2];
    } else if (As_cm <= 38.3) {
       return {D = 157.6, B = 152.9];
    } else {
      return [D = 1000, B = 2000];
    }
}
var d = D / 2;
var b = B / 2;
console.log(d);
document.getElementById("flangeWidth").innerHTML = d ;
console.log(b);
document.getElementById("depth").innerHTML = b ;

As_cm <= 29.2的期望值

d= 152.4 / 2

b= 152.2 / 2

我收到的错误消息是

Uncaught TypeError: Cannot set property 'innerHTML' of null at steelcolumn.js:68

1 个答案:

答案 0 :(得分:1)

您可以返回一个对象,然后将解构的属性作为值。

function steelSection() {
    if (As_cm <= 29.2) return { d: 152.4, b: 152.2 };
    if (As_cm <= 38.3) return { d: 157.6, b: 152.9 };
    return { d: 1000, b: 2000 };
}

var { d, b } = steelSection();

document.getElementById("flangeWidth").innerHTML = d / 2;
document.getElementById("depth").innerHTML = b / 2;