是否有在条件(if)结构的条件语句中定义变量的有效方法?

Is there a valid way of defining a variable within the condition statement of a conditional(if) structure?

在JavaScript中的if语句的条件下,是否有一种简洁的方法来定义变量?例如:

var arr = [1,2,3];
console.log(len); // output is null, since it was never declared
if ((var len = arr.length) > 0) { // len  == 3
    // logic using variable 'len ' here
}

或者在条件语句之前声明和赋值 len 的唯一方法是什么?

如果你关心的是你写的行数,你可以在声明arr的同一行声明len,例如:

var len, arr = [1,2,3];
console.log(len); 
if ((len = arr.length) > 0) { // len  == 3
    // logic using variable 'len ' here

    console.log(len); 
}

我个人避免在条件中设置值。条件不是设置变量的地方。它看起来像一个错误,它会导致错误,阅读您的代码的人可能会错过在条件语句中设置变量的信息。

祝你好运!

根据@VictorJohnson 在另一个答案中的评论,我会像下面这样声明我的变量

var arr = [1,2,3], len=arr.length;
console.log(len);             // len == 3
if (len > 0) {
    // logic using variable 'len ' here

    console.log(len); 
}

这消除了 if 块的可能混淆并保持相当简洁