Tôi đã đọc trang trình bày của John Resig.Một giải pháp khả thi cho việc lặp lại chức năng
Như tôi đã đến slide-27, john trình bày một bài kiểm tra theo dưới đây:
QUIZ: Làm thế nào chúng ta có thể thực hiện vòng lặp với một callback?
function loop(array, fn){
for (var i = 0; i < array.length; i++) {
// Implement me!
}
}
var num = 0;
loop([0, 1, 2], function(value){
assert(value == num++, "Make sure the contents are as we expect it.");
assert(this instanceof Array, "The context should be the full array.");
});
tôi đã cố gắng để thực hiện, và đã đưa ra đoạn mã sau:
function loop(array, fn){
for (var i = 0; i < array.length; i++) {
fn.call(array, array[i]);
}
}
var num = 0;
loop([0, 1, 2], function(value){
assert(value == num++, "Make sure the contents are as we expect it.");
assert(this instanceof Array, "The context should be the full array.");
});
Tôi rất vui mừng rằng nó làm việc, và háo hức để xem slide tiếp theo để so sánh nó với giải pháp john sẽ cung cấp trong tiếp theo trượt.
nhưng trong slide tiếp theo john cung cấp các giải pháp sau đây:
function loop(array, fn){
for (var i = 0; i < array.length; i++)
fn.call(array, array[i], i);
}
var num = 0;
loop([0, 1, 2], function(value, i){
assert(value == num++, "Make sure the contents are as we expect it.");
assert(this instanceof Array, "The context should be the full array.");
});
đến chức năng fn ông truyền cho loop()
, ông nói thêm một tham số i
.
điều đó làm cho tôi tự hỏi tại sao một thông số khác là bắt buộc ??
Chỉ để tiện cho bạn. Bạn có thể muốn in 'i' trong vòng lặp. – elclanrs