0

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;}
4

4 に答える 4

1

はい。ただし、JavaScript の変数ホイストと関数スコープに注意してください (if ステートメントの {} コード ブロックは変数スコープではありません)。

明確にするために、コードは次と同等です。

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

if ($currentLink == $nextLink){              // Check if next link is same as current link
  $nextLoad = $this.eq(2).attr('href');  // If so, get the next link after the next
}
else {$nextLoad = $nextLink;}
于 2013-08-10T03:35:49.867 に答える
1

はい、できますが、JavaScript にはブロック スコープがないため、var 宣言は関数レベルまで引き上げられます。次に例を示します。

function foo() {
    var x = 1;
    if (x === 1) {
        var y = 2;
    }
    console.log(y); // Can see y here, it's local to the fn, not the block
}
于 2013-08-10T03:36:19.730 に答える
0

はい、できますが、JavaScript コード品質ツールである jslint から、すべてを 1 か所に移動するよう求められますvar my_var;...

于 2013-08-10T03:39:00.640 に答える