[英]How to iterate over arrays, providing access to the element, index, and array itself without using built in Javascript functions
I am working on a JS project where I cannot use any built in JS functions, I must code the solution myself. 我正在开发一个JS项目,在其中我无法使用任何内置的JS函数,我必须自己编写解决方案。 I cannot seem to get my below function to work. 我似乎无法使我的以下功能正常工作。 It should not return a value, but simply run the iterator function over each element in the array to provide access to the element, index and array itself. 它不应该返回值,而只是对数组中的每个元素运行迭代器函数以提供对元素,索引和数组本身的访问。 What am I doing wrong? 我究竟做错了什么? (I am new to JS). (我是JS新手)。 I am looking for basic JS solution, not jQuery please. 我在寻找基本的JS解决方案,而不是jQuery。
Sorry, the whole code looks like this: 抱歉,整个代码如下:
myForEach = function(collection, iterator) {
for(var i = 0; i < collection.length; i++) {
iterator(collection[i]);
}
};
Give the function a name, and add the missing }
at the end. 为函数命名,然后在末尾添加缺少的}
。 Then add the additional arguments that you want to pass to the iterator. 然后添加要传递给迭代器的其他参数。
function runIterator(collection, iterator) { for (var i = 0; i < collection.length; i++) { iterator(collection[i], i, collection); } } runIterator([1, "foo", "bar"], function(x, i, c) { alert(x); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.