简体   繁体   English

Javascript forEach循环-如何重建它?

[英]Javascript forEach loop - How to reconstruct it?

In Ruby, we can reconstruct the each loop for an array using the 1) while loop, 2) yield statement (to pass value to a block), and 3) class Array (to make the method available to the Array class); 在Ruby中,我们可以使用1)while循环,2)yield语句(将值传递到块)和3)Array类(使该方法可用于Array类)重建数组的每个循环。 as follows: 如下:

class Array
    def reconstructed_each
        n = 0
        while n < self.length
            yield(self[n])
            n += 1
        end
        self
    end
end

In Javascript, I reconstructed the forEach loop for an array using a similar fashion; 在Javascript中,我以类似的方式为数组重构了forEach循环; as follows: 如下:

Array.prototype.reconstructedforEach = function(c) {
    var n = 0;
    while (n < this.length) {
        c(this[n]);
        n += 1;
    }
};

The part I am not sure about is how to make the above function available to arrays only, but not other types of object eg number. 我不确定的部分是如何使上述函数仅对数组可用,而对其他类型的对象(如数字)不可用。

UPDATE: I have it figured out. 更新:我想通了。 The above code snippet has been edited accordingly. 上面的代码段已进行了相应的编辑。

Are you just looking for a way to iterate a javascript array using the while-construct? 您是否只是在寻找一种使用while-construct迭代javascript数组的方法?

if so: 如果是这样的话:

const arr = ["some", "value", "here"];
let i =0;

while(i < arr.length){
 //use contents of arr[i] to do something useful
 i++;
}

Perhaps I'm missing something 也许我想念一些东西

Maybe you're looking for something like generator functions? 也许您正在寻找类似生成器功能的东西?

const myArray = [1,2,3,4,5];
function* constructEach(){
  let index = 0;
  while(index < 3)
    yield myArray[index++];
}

var gen = constructEach();

console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // undefined

(This example was shamelessly stolen from MDN ) (此示例是从MDN偷偷偷走的)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM