JavaScript でループを構築するにはどうすればよいですか?[閉まっている]

StackOverflow https://stackoverflow.com/questions/52080

  •  09-06-2019
  •  | 
  •  

質問

JavaScript でループを作成するにはどうすればよいですか?

役に立ちましたか?

解決

for ループ

for (i = startValue; i <= endValue; i++) {
    // Before the loop: i is set to startValue
    // After each iteration of the loop: i++ is executed
    // The loop continues as long as i <= endValue is true
}

for...in ループ

for (i in things) {
    // If things is an array, i will usually contain the array keys *not advised*
    // If things is an object, i will contain the member names
    // Either way, access values using: things[i]
}

使用するのは悪い習慣です for...in ループを使用して配列を反復処理します。それは、 ECMA 262 標準であり、非標準の属性またはメソッドが Array オブジェクトに追加されると問題が発生する可能性があります。による プロトタイプ. (おかげで チェイス・セイバート コメントでこれを指摘してくれて)

While ループ

while (myCondition) {
    // The loop will continue until myCondition is false
}

他のヒント

for ループの例を次に示します。

豊富なアイテムを取り揃えております ノード.

for(var i = 0; i< nodes.length; i++){
    var node = nodes[i];
    alert(node);
}

ループ速度の最適化を検討することもできます。見る http://www.robertnyman.com/2008/04/11/javascript-loop-performance/

組み込みループを除いて (while() ..., do ... while(), for() ...)、自己呼び出し関数の構造があり、としても知られています。 再帰 3 つの組み込みループ構造を使用せずにループを作成します。

次のことを考慮してください。

// set the initial value
var loopCounter = 3;

// the body of the loop
function loop() {

    // this is only to show something, done in the loop
    document.write(loopCounter + '<br>');

    // decrease the loopCounter, to prevent running forever
    loopCounter--;

    // test loopCounter and if truthy call loop() again 
    loopCounter && loop();
}

// invoke the loop
loop();

言うまでもなく、この構造は戻り値と組み合わせて使用​​されることが多いため、これは最初に利用可能ではなく再帰の最後に利用可能な値を処理する方法の小さな例です。

function f(n) {
    // return values for 3 to 1
    //       n   -n  ~-n   !~-n   +!~-n   return
    // conv int neg bitnot  not  number 
    //       3   -3   2    false    0    3 * f(2)
    //       2   -2   1    false    0    2 * f(1)
    //       1   -1   0     true    1        1
    // so it takes a positive integer and do some conversion like changed sign, apply
    // bitwise not, do logical not and cast it to number. if this value is then
    // truthy, then return the value. if not, then return the product of the given
    // value and the return value of the call with the decreased number
    return +!~-n || n * f(n - 1);
}

document.write(f(7));

JavaScript のループは次のようになります。

for (var = startvalue; var <= endvalue; var = var + increment) {
    // code to be executed
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top