كيف أقوم ببناء حلقة في جافا سكريبت؟[مغلق]

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

  •  09-06-2019
  •  | 
  •  

سؤال

كيف يمكنني بناء حلقة في جافا سكريبت؟

هل كانت مفيدة؟

المحلول

للحلقات

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 (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 حلقات للتكرار على المصفوفات.إنه يتعارض مع إكما 262 قياسي ويمكن أن يسبب مشاكل عند إضافة سمات أو أساليب غير قياسية إلى كائن الصفيف، على سبيل المثال.بواسطة النموذج المبدئي. (شكرا ل تشيس سيبرت للإشارة إلى ذلك في التعليقات)

بينما الحلقات

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