简体   繁体   English

如何遍历数组,提供对元素,索引和数组本身的访问,而无需使用内置的Javascript函数

[英]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.

相关问题 在不使用内置indexOf函数的情况下查找数组元素的索引 - Find the index of an array element without using built in indexOf function 如何使用相同的函数迭代对象/数组(不使用forEach) - How to iterate over objects/arrays using the same function (without forEach) 如何在没有任何内置函数的情况下将元素添加到数组 - How to add an element to an array without any built in functions 在不使用嵌套for循环的情况下迭代JavaScript数组 - Iterate over a JavaScript array without using nested for-loops 如何遍历对象数组然后删除JavaScript中的每个元素 - How to iterate over an array of object then remove each element in JavaScript 如何使用 Javascript 在数组元素上迭代两次? - How can I use Javascript to iterate twice over an array element? 如何在不使用内置Array方法的情况下删除javascript中的数组元素? - How to delete an array element in javascript without using any of built-in Array methods? 如何访问没有索引的数组元素 ([]) - How to access array element without index ([]) 数组帮助。 如何将 arrays 自身相乘,一个中没有第一个元素,另一个中没有最后一个元素 - array help. How to multiply arrays by itself, without the first element in one, and without the last element in the other 在没有内置函数的情况下删除 JavaScript 数组项? - Removing JavaScript array item without built in functions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM