문제

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() ...), 자체 호출 기능이라고도 하는 구조가 있습니다. 재귀 세 가지 내장 루프 구조 없이 루프를 생성합니다.

다음을 고려하세요:

// 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