变量是否可以从if else语句生成?

Bae*_*ins 0 javascript jquery

我可以根据javascript中的if/else语句更改变量值吗?

var $nextLink = $this.next().attr('href'),
 $currentLink = $this.attr('href');

if ($currentLink == $nextLink){              // Check if next link is same as current link
  var $nextLoad = $this.eq(2).attr('href');  // If so, get the next link after the next
}
else {var $nextLoad = $nextLink;}
Run Code Online (Sandbox Code Playgroud)

nnn*_*nnn 5

问题中显示的代码将起作用.但请注意,JavaScript没有块范围,只有函数范围.也就是说,在一个ifelse语句{}块(或for语句{}等)中声明的变量将在周围的函数中可见.在你的情况下,我认为这实际上是你想要的,但是大多数JS编码器可能会发现在if/else之前声明变量更简洁,然后用if/else设置它的值.

Neater仍然是使用?:条件(或三元)运算符在一行中完成它:

var $nextLoad = $currentLink == $nextLink ? $this.eq(2).attr('href') : $nextLink;
Run Code Online (Sandbox Code Playgroud)