在JavaScript中每一个数组? [英]For-each over an array in JavaScript?

How can I loop through all the entries in an array using JavaScript?

如何使用JavaScript对数组中的所有项进行循环?

I thought it was something like this:

我以为是这样的:

forEach(instance in theArray)

Where theArray is my array, but this seems to be incorrect.

数组是我的数组,但这看起来不正确。

23 个解决方案

#1


5798  

TL;DR

博士TL;

  • Don't use for-in unless you use it with safeguards or are at least aware of why it might bite you.
  • 除非你用它来保护自己,或者至少知道它为什么会咬你,否则不要用它。
  • Your best bets are usually

    你最好的赌注通常是。

    • for-of loop (ES2015+ only),
    • for-of循环(ES2015+ only),
    • Array#forEach (spec | MDN) (or its relatives some and such) (ES5+ only),
    • 数组#forEach (spec | MDN)(或其亲属一些)(ES5+ only),
    • a simple old-fashioned for loop,
    • 一个简单的老式for循环,
    • or for-in with safeguards.
    • 或工党的保障措施。

But there's lots more to explore, read on...

但是还有很多东西需要探索,请继续阅读……


JavaScript has powerful semantics for looping through arrays and array-like objects. I've split the answer into two parts: Options for genuine arrays, and options for things that are just array-like, such as the arguments object, other iterable objects (ES2015+), DOM collections, and so on.

JavaScript具有强大的语义,可以通过数组和类似数组的对象进行循环。我将答案分成两部分:对于真正的数组的选项,以及一些类似arraylike的选项,比如参数对象、其他可迭代对象(ES2015+)、DOM集合等等。

I'll quickly note that you can use the ES2015 options now, even on ES5 engines, by transpiling ES2015 to ES5. Search for "ES2015 transpiling" / "ES6 transpiling" for more...

我很快就会注意到,您现在可以使用ES2015选项,即使是在ES5引擎上,也可以使用ES5到ES5。寻找“ES2015年运输”/“ES6运输”以获得更多……

Okay, let's look at our options:

好的,让我们看看我们的选择:

For Actual Arrays

You have three options in ECMAScript 5 ("ES5"), the version most broadly supported at the moment, and will soon have two more in ECMAScript 2015 ("ES2015", "ES6"), the latest version of JavaScript that vendors are working on supporting:

您在ECMAScript 5(“ES5”)中有三个选项,这个版本目前得到了最广泛的支持,并且很快将在2015年ECMAScript(“ES2015”,“ES6”)中有两个版本,这是供应商正在努力支持的最新版本的JavaScript。

  1. Use forEach and related (ES5+)
  2. 使用forEach和related (ES5+)
  3. Use a simple for loop
  4. 使用一个简单的for循环。
  5. Use for-in correctly
  6. 正确使用工党
  7. Use for-of (use an iterator implicitly) (ES2015+)
  8. 使用for-of(使用迭代器隐式)(ES2015+)
  9. Use an iterator explicitly (ES2015+)
  10. 显式地使用迭代器(ES2015+)

Details:

细节:

1. Use forEach and related

If you're using an environment that supports the Array features of ES5 (directly or using a shim), you can use the new forEach (spec | MDN):

如果您使用的环境支持ES5的数组特性(直接或使用shim),您可以使用新的forEach (spec | MDN):

var a = ["a", "b", "c"];
a.forEach(function(entry) {
    console.log(entry);
});

forEach accepts an iterator function and, optionally, a value to use as this when calling that iterator function (not used above). The iterator function is called for each entry in the array, in order, skipping non-existent entries in sparse arrays. Although I only used one argument above, the iterator function is called with three: The value of each entry, the index of that entry, and a reference to the array you're iterating over (in case your function doesn't already have it handy).

forEach接受一个迭代器函数,并且,在调用迭代器函数时(不使用上述函数),可以选择使用这个值。在数组中的每个条目调用迭代器函数,在稀疏数组中跳过不存在的条目。虽然我只使用了上面的一个参数,但迭代器函数是用3来调用的:每个条目的值、该条目的索引,以及您正在遍历的数组的引用(如果您的函数还不方便的话)。

Unless you're supporting obsolete browsers like IE8 (which NetApps shows at just over 4% market share as of this writing in September 2016), you can happily use forEach in a general-purpose web page without a shim. If you do need to support obsolete browsers, shimming/polyfilling forEach is easily done (search for "es5 shim" for several options).

除非你支持像IE8这样过时的浏览器(在2016年9月的这篇文章中,NetApps的市场份额超过4%),你可以很高兴地在一个没有shim的通用网页上使用forEach。如果您确实需要支持过时的浏览器,那么可以很容易地完成(搜索“es5 shim”选项)。

forEach has the benefit that you don't have to declare indexing and value variables in the containing scope, as they're supplied as arguments to the iteration function, and so nicely scoped to just that iteration.

forEach有一个好处,那就是您不必在包含范围内声明索引和值变量,因为它们作为迭代函数的参数提供,并且很好地限定了迭代的范围。

If you're worried about the runtime cost of making a function call for each array entry, don't be; details.

如果您担心为每个数组条目生成函数调用的运行时成本,请不要这样做;细节。

Additionally, forEach is the "loop through them all" function, but ES5 defined several other useful "work your way through the array and do things" functions, including:

此外,forEach是“通过它们所有”函数的“循环”,但是ES5定义了一些其他有用的“通过数组和做事情”的功能,包括:

  • every (stops looping the first time the iterator returns false or something falsey)
  • 每一个(迭代器第一次返回false或一些falsey)
  • some (stops looping the first time the iterator returns true or something truthy)
  • 一些(迭代器第一次返回true或一些truthy)
  • filter (creates a new array including elements where the filter function returns true and omitting the ones where it returns false)
  • 过滤器(创建一个新的数组,包括过滤器函数返回true的元素,并省略返回false的元素)
  • map (creates a new array from the values returned by the iterator function)
  • 映射(从迭代器函数返回的值创建一个新数组)
  • reduce (builds up a value by repeated calling the iterator, passing in previous values; see the spec for the details; useful for summing the contents of an array and many other things)
  • reduce(通过重复调用迭代器,传递以前的值来构建一个值;详见说明书;用于对数组的内容和许多其他内容进行求和)
  • reduceRight (like reduce, but works in descending rather than ascending order)
  • 减少(如减少,但工作在降序而不是升序)

2. Use a simple for loop

Sometimes the old ways are the best:

有时候旧的方法是最好的:

var index;
var a = ["a", "b", "c"];
for (index = 0; index < a.length; ++index) {
    console.log(a[index]);
}

If the length of the array won't change during the loop, and it's in performance-sensitive code (unlikely), a slightly more complicated version grabbing the length up front might be a tiny bit faster:

如果数组的长度在循环过程中不会发生变化,并且在性能敏感的代码中(不太可能),那么一个稍微复杂一点的版本会更快地抢占前面的长度:

var index, len;
var a = ["a", "b", "c"];
for (index = 0, len = a.length; index < len; ++index) {
    console.log(a[index]);
}

And/or counting backward:

和/或向后计数:

var index;
var a = ["a", "b", "c"];
for (index = a.length - 1; index >= 0; --index) {
    console.log(a[index]);
}

But with modern JavaScript engines, it's rare you need to eke out that last bit of juice.

但是使用现代JavaScript引擎,你很少需要把最后一点的果汁挤出来。

In ES2015 and higher, you can make your index and value variables local to the for loop:

在ES2015和更高版本中,您可以将索引和值变量本地化为for循环:

let a = ["a", "b", "c"];
for (let index = 0; index < a.length; ++index) {
    let value = a[index];
}
//console.log(index); // Would cause "ReferenceError: index is not defined"
//console.log(value); // Would cause "ReferenceError: value is not defined"

And when you do that, not just value but also index is recreated for each loop iteration, meaning closures created in the loop body keep a reference to the index (and value) created for that specific iteration:

当您这样做时,不仅是值,而且还为每个循环迭代重新创建索引,这意味着在循环体中创建的闭包将引用为该特定迭代创建的索引(和值):

let divs = document.querySelectorAll("div");
for (let index = 0; index < divs.length; ++index) {
    divs[index].addEventListener('click', e => {
        alert("Index is: " + index);
    });
}

If you had five divs, you'd get "Index is: 0" if you clicked the first and "Index is: 4" if you clicked the last. This does not work if you use var instead of let.

如果你有5个div,你会得到“Index is: 0”,如果你点击了第一个,“Index is: 4”,如果你点击了最后一个。如果您使用var而不是let,那么这将不起作用。

3. Use for-in correctly

You'll get people telling you to use for-in, but that's not what for-in is forfor-in loops through the enumerable properties of an object, not the indexes of an array. The order is not guaranteed, not even in ES2015 (ES6). ES2015 does define an order to object properties (via [[OwnPropertyKeys]][[Enumerate]], and things that use them like Object.getOwnPropertyKeys), but it does not define that for-in will follow that order. (Details in this other answer.)

你会让别人告诉你要用in -in,但这不是forin的意思。forin循环通过对象的可枚举属性,而不是数组的索引。该订单没有得到保证,即使在2015年(ES6)。ES2015确实定义了一个对象属性的命令(通过[[OwnPropertyKeys]],[[枚举]],以及使用它们的对象,比如object . getownpropertykeys,但是它并没有定义这个顺序。(详见另一个答案。)

Still, it can be useful, particularly for sparse arrays, if you use appropriate safeguards:

不过,如果您使用适当的安全防护措施,它仍然是有用的,特别是对于稀疏数组。

// `a` is a sparse array
var key;
var a = [];
a[0] = "a";
a[10] = "b";
a[10000] = "c";
for (key in a) {
    if (a.hasOwnProperty(key)  &&        // These are explained
        /^0$|^[1-9]\d*$/.test(key) &&    // and then hidden
        key <= 4294967294                // away below
        ) {
        console.log(a[key]);
    }
}

Note the two checks:

注意这两个检查:

  1. That the object has its own property by that name (not one it inherits from its prototype), and

    这个对象有自己的属性(而不是从原型继承的),以及。

  2. That the key is a base-10 numeric string in its normal string form and its value is <= 2^32 - 2 (which is 4,294,967,294). Where does that number come from? It's part of the definition of an array index in the specification. Other numbers (non-integers, negative numbers, numbers greater than 2^32 - 2) are not array indexes. The reason it's 2^32 - 2 is that that makes the greatest index value one lower than 2^32 - 1, which is the maximum value an array's length can have. (E.g., an array's length fits in a 32-bit unsigned integer.) (Props to RobG for pointing out in a comment on my blog post that my previous test wasn't quite right.)

    关键是一个八进制数数正常字符串形式的数字字符串,它的值是< = 2 ^ 32 - 2(4294967294)。这个数字是从哪里来的?它是规范中数组索引定义的一部分。其他号码(非整数、负数、数字大于2 ^ 32 - 2)不是数组索引。原因是2。32 - 2是使最大的索引值小于2。32 - 1,这是数组长度的最大值。(例如,一个数组的长度适合于一个32位无符号整数。)(在我的博客文章中,RobG指出我之前的测试不太正确,这是一个很好的例子。)

That's a tiny bit of added overhead per loop iteration on most arrays, but if you have a sparse array, it can be a more efficient way to loop because it only loops for entries that actually exist. E.g., for the array above, we loop a total of three times (for keys "0""10", and "10000" — remember, they're strings), not 10,001 times.

在大多数数组中,这是每个循环迭代的一小部分额外开销,但是如果您有一个稀疏数组,它可能是一种更有效的循环方式,因为它只对实际存在的条目进行循环。例如,对于上面的数组,我们循环了三次(对于键“0”、“10”和“10000”——记住,它们是字符串),而不是10,001次。

Now, you won't want to write that every time, so you might put this in your toolkit:

现在,你不想每次都写这个,所以你可以把它放在你的工具箱里:

function arrayHasOwnIndex(array, prop) {
    return array.hasOwnProperty(prop) && /^0$|^[1-9]\d*$/.test(prop) && prop <= 4294967294; // 2^32 - 2
}

And then we'd use it like this:

然后我们可以这样使用:

for (key in a) {
    if (arrayHasOwnIndex(a, key)) {
        console.log(a[key]);
    }
}

Or if you're interested in just a "good enough for most cases" test, you could use this, but while it's close, it's not quite correct:

或者如果你对一个“足够好,对大多数情况”的测试感兴趣,你可以用这个,但是当它接近时,它不完全正确:

for (key in a) {
    // "Good enough" for most cases
    if (String(parseInt(key, 10)) === key && a.hasOwnProperty(key)) {
        console.log(a[key]);
    }
}

4. Use for-of (use an iterator implicitly) (ES2015+)

ES2015 adds iterators to JavaScript. The easiest way to use iterators is the new for-of statement. It looks like this:

ES2015将迭代器添加到JavaScript。使用迭代器的最简单方法是新的for-of语句。它看起来像这样:

var val;
var a = ["a", "b", "c"];
for (val of a) {
    console.log(val);
}

Output:

输出:

a
b
c

Under the covers, that gets an iterator from the array and loops through it, getting the values from it. This doesn't have the issue that using for-in has, because it uses an iterator defined by the object (the array), and arrays define that their iterators iterate through their entries (not their properties). Unlike for-in in ES5, the order in which the entries are visited is the numeric order of their indexes.

在覆盖层之下,从数组中获取一个迭代器并遍历它,从中获取值。这没有使用forin的问题,因为它使用对象(数组)定义的迭代器,数组定义迭代器迭代它们的条目(而不是它们的属性)。与在ES5中的插入不同,访问条目的顺序是其索引的数字顺序。

5. Use an iterator explicitly (ES2015+)

Sometimes, you might want to use an iterator explicitly. You can do that, too, although it's a lot clunkier than for-of. It looks like this:

有时候,您可能需要显式地使用迭代器。你也可以这么做,尽管它比for-of要笨重得多。它看起来像这样:

var a = ["a", "b", "c"];
var it = a.values();
var entry;
while (!(entry = it.next()).done) {
    console.log(entry.value);
}

The iterator is a function (specifically, a generator) that returns a new object each time you call next. The object returned by the iterator has a property, done, telling us whether it's done, and a property value with the value for that iteration.

迭代器是一个函数(具体地说,是一个生成器),每当您调用next时,它都会返回一个新对象。迭代器返回的对象有一个属性,完成了,告诉我们它是否已经完成,以及一个具有该迭代值的属性值。

The meaning of value varies depending on the iterator; arrays support (at least) three functions that return iterators:

值的意义因迭代器而异;数组支持(至少)返回迭代器的三个函数:

  • values(): This is the one I used above. It returns an iterator where each value is the value for that iteration.
  • 值():这是我在上面使用的。它返回一个迭代器,其中每个值都是该迭代的值。
  • keys(): Returns an iterator where each value is the key for that iteration (so for our a above, that would be "0", then "1", then "2").
  • keys():返回一个迭代器,其中每个值都是该迭代的关键(因此对于我们的a,它将是“0”,然后是“1”,然后是“2”)。
  • entries(): Returns an iterator where each value is an array in the form [key, value] for that iteration.
  • 条目():返回一个迭代器,其中每个值都是该迭代的形式[key, value]的数组。

(As of this writing, Firefox 29 supports entries and keys but not values.)

(在撰写本文时,Firefox 29支持条目和键,但不支持值。)

For Array-Like Objects

Aside from true arrays, there are also array-like objects that have a length property and properties with numeric names: NodeList instances, the arguments object, etc. How do we loop through their contents?

除了真正的数组之外,还有类似arraylike的对象,它们具有长度属性和具有数字名称的属性:NodeList实例、参数对象等等。我们如何循环它们的内容?

Use any of the options above for arrays

At least some, and possibly most or even all, of the array approaches above frequently apply equally well to array-like objects:

至少有一些,甚至可能是所有的数组方法都同样适用于arraylike对象:

  1. Use forEach and related (ES5+)

    使用forEach和related (ES5+)

    The various functions on Array.prototype are "intentionally generic" and can usually be used on array-like objects via Function#call or Function#apply. (See the Caveat for host-provided objects at the end of this answer, but it's a rare issue.)

    数组的各种函数。原型是“有意通用的”,通常可以通过函数#调用或函数#应用在arraylike对象上。(在这个答案的结尾,请查看host提供的对象的警告,但这是一个罕见的问题。)

    Suppose you wanted to use forEach on a Node's childNodes property. You'd do this:

    假设您想在节点的childNodes属性上使用forEach。你会这样做:

    Array.prototype.forEach.call(node.childNodes, function(child) {
        // Do something with `child`
    });
    

    If you're going to do that a lot, you might want to grab a copy of the function reference into a variable for reuse, e.g.:

    如果您要经常这样做,您可能想要将函数引用复制到一个变量中以便重用,例如:

    // (This is all presumably in some scoping function)
    var forEach = Array.prototype.forEach;
    
    // Then later...
    forEach.call(node.childNodes, function(child) {
        // Do something with `child`
    });
    
  2. Use a simple for loop

    使用一个简单的for循环。

    Obviously, a simple for loop applies to array-like objects.

    显然,一个简单的for循环应用于arraylike对象。

  3. Use for-in correctly

    正确使用工党

    for-in with the same safeguards as with an array should work with array-like objects as well; the caveat for host-provided objects on #1 above may apply.

    在与阵列相同的防护措施下,也应该使用类似arrayoid的对象;上面第一条所提供的关于主机的警告可能会适用。

  4. Use for-of (use an iterator implicitly) (ES2015+)

    使用for-of(使用迭代器隐式)(ES2015+)

    for-of will use the iterator provided by the object (if any); we'll have to see how this plays with the various array-like objects, particularly host-provided ones.

    for-of将使用对象提供的迭代器(如果有的话);我们将会看到这是如何与各种各样的arraylike对象,特别是宿主提供的对象。

  5. Use an iterator explicitly (ES2015+)

    显式地使用迭代器(ES2015+)

    See #4, we'll have to see how iterators play out.

    参见#4,我们将看到迭代器是如何发挥作用的。

Create a true array

Other times, you may want to convert an array-like object into a true array. Doing that is surprisingly easy:

其他时候,您可能想要将一个类似数组的对象转换成一个真正的数组。做到这一点非常容易:

  1. Use the slice method of arrays

    使用数组的切片方法。

    We can use the slice method of arrays, which like the other methods mentioned above is "intentionally generic" and so can be used with array-like objects, like this:

    我们可以使用数组的切片方法,就像上面提到的其他方法是“有意通用的”,因此可以使用类似arraylike的对象,比如:

    var trueArray = Array.prototype.slice.call(arrayLikeObject);
    

    So for instance, if we want to convert a NodeList into a true array, we could do this:

    举个例子,如果我们想把一个NodeList转换成一个真正的数组,我们可以这样做:

    var divs = Array.prototype.slice.call(document.querySelectorAll("div"));
    

    See the Caveat for host-provided objects below. In particular, note that this will fail in IE8 and earlier, which don't let you use host-provided objects as this like that.

    请参见下面的主机提供的对象的警告。特别要注意的是,这将在IE8和更早的版本中失败,它不会让您使用主机提供的对象。

  2. Use spread notation (...)

    使用传播符号(…)

    It's also possible to use ES2015's spread notation (MDN currently calls it an operator; it isn't one), with JavaScript engines that support this feature:

    也可以使用ES2015的扩展表示法(MDN目前称为操作符;它不是一个),JavaScript引擎支持这个特性:

    var trueArray = [...iterableObject];
    

    So for instance, if we want to convert a NodeList into a true array, with spread syntax this becomes quite succinct:

    例如,如果我们想要将一个NodeList转换成一个真正的数组,用扩展的语法,这将变得非常简洁:

    var divs = [...document.querySelectorAll("div")];
    
  3. Use Array.from (spec) | (MDN)

    使用Array.from (spec) | (MDN)

    Array.from (ES2015, but shimmable) creates an array from an array-like object, optionally passing the entries through a mapping function first. So:

    来自(ES2015,但shimmable)从一个数组类对象创建一个数组,可以选择先通过映射函数传递条目。所以:

    var divs = Array.from(document.querySelectorAll("div"));
    

    Or if you wanted to get an array of the tag names of the elements with a given class, you'd use the mapping function:

    或者,如果你想要得到一个给定类的元素的标签名数组,你可以使用映射函数:

    // Arrow function (ES2015):
    var divs = Array.from(document.querySelectorAll(".some-class"), element => element.tagName);
    
    // Standard function (since `Array.from` can be shimmed):
    var divs = Array.from(document.querySelectorAll(".some-class"), function(element) {
        return element.tagName;
    });
    

Caveat for host-provided objects

If you use Array.prototype functions with host-provided array-like objects (DOM lists and other things provided by the browser rather than the JavaScript engine), you need to be sure to test in your target environments to make sure the host-provided object behaves properly. Most do behave properly (now), but it's important to test. The reason is that most of the Array.prototype methods you're likely to want to use rely on the host-provided object giving an honest answer to the abstract [[HasProperty]] operation. As of this writing, browsers do a very good job of this, but the ES5 spec did allow for the possibility a host-provided object may not be honest; it's in §8.6.2 (several paragraphs below the big table near the beginning of that section), where it says:

如果你使用数组。原型函数使用宿主提供的array样对象(DOM列表和其他由浏览器提供的东西而不是JavaScript引擎),您需要确保在您的目标环境中进行测试,以确保宿主提供的对象的行为正常。大多数人的行为举止得体(现在),但重要的是测试。原因是数组的大部分。您可能想要使用的原型方法依赖于主机提供的对象,以对抽象的[[HasProperty]]操作给出一个诚实的答案。在撰写本文时,浏览器的工作做得很好,但是ES5规范确实允许一个宿主提供的对象可能不诚实;在§8.6.2(下面几个段落的开始部分)附近的大桌子,它说:

Host objects may implement these internal methods in any manner unless specified otherwise; for example, one possibility is that [[Get]] and [[Put]] for a particular host object indeed fetch and store property values but [[HasProperty]] always generates false.

除非另有说明,主机对象可以以任何方式实现这些内部方法;例如,一种可能性是[[Get]]和[[Put]],对于一个特定的主机对象,实际上是获取和存储属性值,但是[[HasProperty]]总是产生错误。

(I couldn't find the equivalent verbiage in the ES2015 spec, but it's bound to still be the case.) Again, as of this writing the common host-provided array-like objects in modern browsers (NodeList instances, for instance) do handle [[HasProperty]] correctly, but it's important to test.

(我在ES2015的规范中找不到类似的verbiage,但肯定是这样的。)同样,在现代浏览器中(例如,NodeList实例)中,常见的主机提供的arraylike对象可以正确处理[[HasProperty]],但是测试是很重要的。

#2


441  

Edit: This answer is hopelessly out-of-date. For a more modern approach, look at the methods available on an array. Methods of interest might be:

编辑:这个答案已经过时了。对于更现代的方法,请查看数组中可用的方法。感兴趣的方法可能是:

  • forEach
  • forEach
  • map
  • 地图
  • filter
  • 过滤器
  • zip
  • 邮政编码
  • reduce
  • 减少
  • every
  • 每一个
  • some
  • 一些

The standard way to iterate an array in JavaScript is a vanilla for-loop:

在JavaScript中迭代数组的标准方法是:

var length = arr.length,
    element = null;
for (var i = 0; i < length; i++) {
  element = arr[i];
  // Do something with element i.
}

Note, however, that this approach is only good if you have a dense array, and each index is occupied by an element. If the array is sparse, then you can run into performance problems with this approach, since you will iterate over a lot of indices that do not really exist in the array. In this case, a for .. in-loop might be a better idea. However, you must use the appropriate safeguards to ensure that only the desired properties of the array (that is, the array elements) are acted upon, since the for..in-loop will also be enumerated in legacy browsers, or if the additional properties are defined as enumerable.

但是请注意,如果您有一个密集的数组,并且每个索引都被一个元素占用,那么这种方法是非常好的。如果数组是稀疏的,那么您就会遇到这种方法的性能问题,因为您将迭代许多在数组中不存在的索引。在这种情况下,a代表。in-loop可能是一个更好的主意。但是,您必须使用适当的保护措施来确保只对数组的期望属性(即数组元素)进行操作。in-loop也将在遗留浏览器中枚举,或者如果附加属性被定义为可枚举。

In ECMAScript 5 there will be a forEach method on the array prototype, but it is not supported in legacy browsers. So to be able to use it consistently you must either have an environment that supports it (for example, Node.js for server side JavaScript), or use a "Polyfill". The Polyfill for this functionality is, however, trivial and since it makes the code easier to read, it is a good polyfill to include.

在ECMAScript 5中,数组原型中将有一个forEach方法,但是在遗留浏览器中不支持它。因此,要能够始终使用它,您必须有一个支持它的环境(例如,Node)。js用于服务器端JavaScript),或使用“Polyfill”。然而,这个功能的Polyfill是微不足道的,因为它使代码更易于阅读,它是一个很好的包含。

#3


202  

If you’re using the jQuery library, you can use jQuery.each:

如果使用jQuery库,可以使用jQuery.each:

$.each(yourArray, function(index, value) {
  // do your stuff here
});

EDIT :

编辑:

As per question, user want code in javascript instead of jquery so the edit is

根据问题,用户需要javascript而不是jquery的代码。

var length = yourArray.length;   
for (var i = 0; i < length; i++) {
  // Do something with yourArray[i].
}

#4


84  

Loop backwards

I think the reverse for loop deserves a mention here:

我认为循环的反面应该在这里提一下:

for (var i = array.length; i--; ) {
     // process array[i]
}

Advantages:

  • You do not need to declare a temporary len variable, or compare against array.length on each iteration, either of which might be a minute optimisation.
  • 您不需要声明一个临时的len变量,也不需要与数组进行比较。每次迭代的长度,可能是一分钟的优化。
  • Removing siblings from the DOM in reverse order is usually more efficient. (The browser needs to do less shifting of elements in its internal arrays.)
  • 以相反的顺序从DOM中删除兄弟姐妹通常更有效。(浏览器需要在内部数组中减少元素的移动。)
  • If you modify the array while looping, at or after index i (for example you remove or insert an item at array[i]), then a forward loop would skip the item that shifted left into position i, or re-process the ith item that was shifted right. In a traditional for loop, you could update i to point to the next item that needs processing - 1, but simply reversing the direction of iteration is often a simpler and more elegant solution.
  • 如果在索引i(例如,在数组[i]中删除或插入一个项目时)修改数组,那么向前循环将跳过移位到位置i的项,或重新处理右移的第i项。在传统的for循环中,您可以更新i来指向需要处理的下一项,但简单地逆转迭代的方向通常是更简单、更优雅的解决方案。
  • Similarly, when modifying or removing nested DOM elements, processing in reverse can circumvent errors. For example, consider modifying the innerHTML of a parent node before handling its children. By the time the child node is reached it will be detached from the DOM, having been replaced by a newly created child when the parent's innerHTML was written.
  • 类似地,在修改或删除嵌套的DOM元素时,反向处理可以避免错误。例如,考虑修改父节点的innerHTML,然后再处理其子节点。当到达子节点时,它将与DOM分离,在编写父元素的innerHTML时被新创建的子节点所替换。
  • It is shorter to type, and read, than some of the other options available. Although it loses to forEach() and to ES6's for ... of.
  • 它比其他可用的选项更短,而且更容易阅读。虽然它失去了forEach()和ES6的for…的。

Disadvantages:

  • It processes the items in reverse order. If you were building a new array from the results, or printing things on screen, naturally the output will be reversed with respect to the original order.
  • 它以相反的顺序处理这些项。如果您正在从结果中构建一个新的数组,或者在屏幕上打印东西,那么自然的输出将会与原来的顺序相反。
  • Repeatedly inserting siblings into the DOM as a first child in order to retain their order is less efficient. (The browser would keep having to shift things right.) To create DOM nodes efficiently and in order, just loop forwards and append as normal (and also use a "document fragment").
  • 为了保持他们的顺序,重复将兄弟姐妹插入DOM作为第一个孩子是低效的。(浏览器会不停地把事情做对。)要有效地创建DOM节点并按顺序创建DOM节点,只需循环转发并将其添加为normal(并使用“文档片段”)。
  • The reverse loop is confusing to junior developers. (You may consider that an advantage, depending on your outlook.)
  • 反向循环让初级开发人员感到困惑。(根据你的观点,你可能会认为这是一个优势。)

Should I always use it?

Some developers use the reverse for loop by default, unless there is a good reason to loop forwards.

一些开发人员在默认情况下使用反向循环,除非有一个好的理由来循环转发。

Although the performance gains are usually insignificant, it sort of screams:

虽然业绩增长通常是微不足道的,但它会发出类似的尖叫声:

"Just do this to every item in the list, I don't care about the order!"

“对列表中的每一个项目都这样做,我不关心顺序!”

However in practice that is not actually a reliable indication of intent, since it is indistinguishable from those occasions when you do care about the order, and really do need to loop in reverse. So in fact another construct would be needed to accurately express the "don't care" intent, something currently unavailable in most languages, including ECMAScript, but which could be called, for example, forEachUnordered().

然而在实际中,这实际上并不是一个可靠的意图指示,因为它与您关心订单时的情况是不可区分的,并且确实需要反向循环。因此,实际上需要另一个结构来准确地表达“不关心”的意图,这是目前大多数语言中无法使用的,包括ECMAScript,但是可以调用它,例如,forEachUnordered()。

If order doesn't matter, and efficiency is a concern (in the innermost loop of a game or animation engine), then it may be acceptable to use the reverse for loop as your go-to pattern. Just remember that seeing a reverse for loop in existing code does not necessarily mean that the order irrelevant!

如果顺序无关紧要,而效率是一个关注点(在游戏或动画引擎的最内层循环中),那么使用反向循环作为您的首选模式可能是可以接受的。只要记住,在现有代码中看到循环的反转并不一定意味着这个顺序无关紧要!

It is better to use forEach()

In general for higher level code where clarity and safety are greater concerns, I would recommend using Array::forEach as your default pattern:

一般来说,对于更高级别的代码,清晰和安全是更重要的问题,我建议使用数组::forEach作为您的默认模式:

  • It is clear to read.
  • 这是显而易见的。
  • It indicates that i is not going to be shifted within the block (which is always a possible surprise hiding in long for and while loops.)
  • 它表示我不会在这个块中移动(这总是一个可能的意外隐藏在long for和while循环中)。
  • It gives you a free scope for closures.
  • 它为您提供了闭包的自由空间。
  • It reduces leakage of local variables and accidental collision with (and mutation of) outer variables.
  • 它减少了局部变量的泄漏和外部变量的意外碰撞(和突变)。

Then when you do see the reverse for loop in your code, that is a hint that it is reversed for a good reason (perhaps one of the reasons described above). And seeing a traditional forward for loop may indicate that shifting can take place.

然后,当您在代码中看到循环的反转时,这是一个提示,它被颠倒了,原因很好(也许是上面描述的原因之一)。而看到传统的循环前进可能表明这种转变是可以发生的。

(If the discussion of intent makes no sense to you, then you and your code may benefit from watching Crockford's lecture on Programming Style & Your Brain.)

(如果讨论的意图对你来说毫无意义,那么你和你的代码可能受益于观看Crockford关于编程风格和大脑的讲座。)


How does it work?

for (var i = 0; i < array.length; i++) { ... }   // Forwards

for (var i = array.length; i--; )    { ... }   // Reverse

You will notice that i-- is the middle clause (where we usually see a comparison) and the last clause is empty (where we usually see i++). That means that i-- is also used as the condition for continuation. Crucially, it is executed and checked before each iteration.

您会注意到,我——是中间的子句(在这里我们通常看到比较),而最后一个子句是空的(我们通常看到的是i++)。这意味着我——也被用作延续的条件。至关重要的是,它在每次迭代之前执行和检查。

  • How can it start at array.length without exploding?

    它如何从数组开始。长度没有爆炸?

    Because i-- runs before each iteration, on the first iteration we will actually be accessing the item at array.length - 1 which avoids any issues with Array-out-of-bounds undefined items.

    因为i——在每次迭代之前运行,在第一次迭代中,我们将实际访问数组中的项。长度- 1可以避免任何与arrayout无关的未定义项的问题。

  • Why doesn't it stop iterating before index 0?

    为什么它不能在索引0之前停止迭代?

    The loop will stop iterating when the condition i-- evaluates to a falsey value (when it yields 0).

    循环将在条件i的情况下停止迭代(当它的值为0时)。

    The trick is that unlike --i, the trailing i-- operator decrements i but yields the value before the decrement. Your console can demonstrate this:

    诀窍在于,不像——i,后面的i——操作符递减i,但在递减之前得到值。您的控制台可以演示这一点:

    > var i = 5; [i, i--, i];

    > var i = 5;(我,我,我);

    [5, 5, 4]

    (5、5、4)

    So on the final iteration, i was previously 1 and the i-- expression changes it to 0 but actually yields 1 (truthy), and so the condition passes. On the next iteration i-- changes i to -1 but yields 0 (falsey), causing execution to immediately drop out of the bottom of the loop.

    在最后一次迭代中,我之前是1,而i——表达式将它变为0,但实际上是1 (truthy),所以条件通过了。在下一个迭代中,我将i更改为-1,但结果为0 (falsey),导致执行立即从循环的底部退出。

    In the traditional forwards for loop, i++ and ++i are interchangeable (as Douglas Crockford points out). However in the reverse for loop, because our decrement is also our condition expression, we must stick with i-- if we want to process the item at index 0.

    在传统的for循环中,i++和++i是可互换的(正如Douglas Crockford所指出的)。然而,在反向循环中,因为我们的减量也是我们的条件表达式,所以我们必须坚持i——如果我们想在索引0中处理这个项。


Trivia

Some people like to draw a little arrow in the reverse for loop, and end with a wink:

有些人喜欢在反循环中画一个小箭头,然后眨眼:

for (var i = array.length; i --> 0 ;) {

Credits go to WYL for showing me the benefits and horrors of the reverse for loop.

感谢WYL向我展示了反向循环的好处和恐惧。

#5


66  

Some C-style languages use foreach to loop through enumerations. In JavaScript this is done with the for..in loop structure:

一些c风格的语言使用foreach来遍历枚举。在JavaScript中,这是用for。在循环结构:

var index,
    value;
for (index in obj) {
    value = obj[index];
}

There is a catch. for..in will loop through each of the object's enumerable members, and the members on its prototype. To avoid reading values that are inherited through the object's prototype, simply check if the property belongs to the object:

有一个捕捉。为. .in将遍历每个对象的可枚举成员,以及其原型中的成员。为了避免读取通过对象原型继承的值,只需检查属性是否属于对象:

for (i in obj) {
    if (obj.hasOwnProperty(i)) {
        //do stuff
    }
}

Additionally, ECMAScript 5 has added a forEach method to Array.prototype which can be used to enumerate over an array using a calback (the polyfill is in the docs so you can still use it for older browsers):

此外,ECMAScript 5为数组添加了一个forEach方法。可以使用calback枚举数组的原型(polyfill在文档中,所以您仍然可以使用它用于较旧的浏览器):

arr.forEach(function (val, index, theArray) {
    //do stuff
});

It's important to note that Array.prototype.forEach doesn't break when the callback returns falsejQuery and Underscore.js provide their own variations on each to provide loops that can be short-circuited.

需要注意的是Array.prototype。当回调返回false时,forEach不会中断。jQuery和下划线。js提供了各自的变体,以提供可以短路的循环。

#6


28  

If you want to loop over an array, use the standard three-part for loop.

如果要对数组进行循环,请使用标准的三部分进行循环。

for (var i = 0; i < myArray.length; i++) {
    var arrayItem = myArray[i];
}

You can get some performance optimisations by caching myArray.length or iterating over it backwards.

可以通过缓存myArray获得一些性能优化。长度或迭代它的向后。

#7


24  

forEach implementation (see in jsFiddle):

forEach实现(参见jsFiddle):

function forEach(list,callback) {
  var length = list.length;
  for (var n = 0; n < length; n++) {
    callback.call(list[n]);
  }
}

var myArray = ['hello','world'];

forEach(
  myArray,
  function(){
    alert(this); // do something
  }
);

#8


24  

I know this is an old post, and there are so many great answers already. For a little more completeness I figured I'd throw in another one using AngularJS. Of course, this only applies if you're using Angular, obviously, nonetheless I'd like to put it anyway.

我知道这是一个古老的帖子,已经有很多很棒的答案了。为了更完整一点,我想我还会用AngularJS来做另一个。当然,这只适用于如果你使用角度,显然,尽管如此我还是想把它写下来。

angular.forEach takes 2 arguments and an optional third argument. The first argument is the object (array) to iterate over, the second argument is the iterator function, and the optional third argument is the object context (basically referred to inside the loop as 'this'.

角。forEach接受两个参数和一个可选的第三个参数。第一个参数是要遍历的对象(数组),第二个参数是迭代器函数,可选的第三个参数是对象上下文(主要是在循环中称为“this”)。

There are different ways to use the forEach loop of angular. The simplest and probably most used is

有不同的方法来使用forEach循环的角度。最简单和最常用的是。

var temp = [1, 2, 3];
angular.forEach(temp, function(item) {
    //item will be each element in the array
    //do something
});

Another way that is useful for copying items from one array to another is

从一个数组复制到另一个数组的另一种方法是。

var temp = [1, 2, 3];
var temp2 = [];
angular.forEach(temp, function(item) {
    this.push(item); //"this" refers to the array passed into the optional third parameter so, in this case, temp2.
}, temp2);

Though, you don't have to do that, you can simply do the following and it's equivalent to the previous example:

但是,你不必这样做,你可以简单地做下面的事情,它等价于上一个例子:

angular.forEach(temp, function(item) {
    temp2.push(item);
});

Now there are pros and cons of using the angular.forEach function as opposed to the built in vanilla-flavored for loop.

现在有了利用角度的利与弊。forEach函数与在vanilla-调味的for循环中所构建的函数不同。

Pros

优点

  • Easy readability
  • 简单的可读性
  • Easy writability
  • 简单的可写性
  • If available, angular.forEach will use the ES5 forEach loop. Now, I will get to efficientcy in the cons section, as the forEach loops are much slower than the for loops. I mention this as a pro because it's nice to be consistent and standardized.
  • 如果可用,角。forEach将使用ES5 forEach循环。现在,我将在缺点部分中得到效率,因为forEach循环比for循环要慢得多。我说这是专业的,因为保持一致和标准化很好。

Consider the following 2 nested loops, which do exactly the same thing. Let's say that we have 2 arrays of objects and each object contains an array of results, each of which has a Value property that's a string (or whatever). And let's say we need to iterate over each of the results and if they're equal then perform some action:

考虑下面的两个嵌套循环,它们的作用完全相同。假设我们有2个对象数组每个对象都包含一个结果数组,每个结果都有一个值属性,这是一个字符串(或其他)。假设我们需要对每一个结果进行迭代如果它们相等则执行一些动作:

angular.forEach(obj1.results, function(result1) {
    angular.forEach(obj2.results, function(result2) {
        if (result1.Value === result2.Value) {
            //do something
        }
    });
});

//exact same with a for loop
for (var i = 0; i < obj1.results.length; i++) {
    for (var j = 0; j < obj2.results.length; j++) {
        if (obj1.results[i].Value === obj2.results[j].Value) {
            //do something
        }
    }
}

Granted this is a very simple hypothetical example, but I've written triple embedded for loops using the second approach and it was very hard to read, and write for that matter.

当然,这是一个非常简单的假设例子,但是我已经用第二种方法编写了三重嵌套循环,而且它非常难读,而且写起来也很困难。

Cons

缺点

  • Efficiency. angular.forEach, and the native forEach, for that matter, are both so much slower than the normal for loop....about 90% slower. So for large data sets, best to stick to the native for loop.
  • 效率。角。对于每个人来说,在这个问题上,每个人都比正常的for循环要慢得多慢90%左右。因此,对于大型数据集,最好使用本机for循环。
  • No break, continue, or return support. continue is actually supported by "accident", to continue in an angular.forEach you simple put a return; statement in the function like angular.forEach(array, function(item) { if (someConditionIsTrue) return; }); which will cause it to continue out of the function for that iteration. This is also due to the fact that the native forEach does not support break or continue either.
  • 没有中断、继续或返回支持。继续得到“意外”的支持,继续保持一个角度。每一个你简单的回报;在函数中的表述像角。forEach(数组、函数(项){if (someConditionIsTrue)返回;});这将使它在那个迭代的函数中继续。这也是由于本地的forEach不支持中断或继续。

I'm sure there's various other pros and cons as well, and please feel free to add any that you see fit. I feel that, bottom line, if you need efficiency, stick with just the native for loop for your looping needs. But, if your datasets are smaller and a some efficiency is okay to give up in exchange for readability and writability, then by all means throw an angular.forEach in that bad boy.

我确信还有各种各样的优点和缺点,请随意添加任何你认为合适的。我觉得,底线是,如果你需要效率,坚持用本地的for循环来满足你的循环需求。但是,如果你的数据集比较小,并且有一些效率可以放弃,以换取可读性和可写性,那么无论如何都要抛出一个角度。在那个坏孩子身上。

#9


23  

If you don't mind emptying the array:

如果你不介意清空数组:

var x;

while(x = y.pop()){ 

    alert(x); //do something 

}

x will contain the last value of y and it will be removed from the array. You can also use shift() which will give and remove the first item from y.

x将包含y的最后一个值,它将从数组中移除。您还可以使用shift(),它将给出并从y中移除第一项。

#10


21  

An easy solution now would be to use the underscore.js library. It's providing many useful tools, such as each and will automatically delegate the job to the native forEach if available.

一个简单的解决方案是使用下划线。js库。它提供了许多有用的工具,比如每个工具,如果有的话,它会自动将工作委派给本地的forEach。

A CodePen example of how it works is:

一个CodePen例子说明了它的工作原理:

var arr = ["elemA", "elemB", "elemC"];
_.each(arr, function(elem, index, ar)
{
...
});

See also

  • Documentation for native Array.prototype.forEach().
  • 文档原生Array.prototype.forEach()。
  • In for_each...in (MDN) it is explained that for each (variable in object) is deprecated as the part of ECMA-357 (EAX) standard.
  • 在for_each…在(MDN)中,解释了每个(对象中的变量)都被认为是ECMA-357 (EAX)标准的一部分。
  • for...of (MDN) describes the next way of iterating using for (variable of object) as the part of the Harmony (ECMAScript 6) proposal.
  • 为…(MDN)描述了作为协调(ECMAScript 6)建议的一部分迭代使用(对象变量)的方法。

#11


19  

There are three implementations of foreach in jQuery as follows.

在jQuery中有三个foreach实现,如下所示。

var a = [3,2];

$(a).each(function(){console.log(this.valueOf())}); //Method 1
$.each(a, function(){console.log(this.valueOf())}); //Method 2
$.each($(a), function(){console.log(this.valueOf())}); //Method 3

#12


18  

Probably the for(i = 0; i < array.length; i++) loop is not the best choice. Why? If you have this:

可能是for(i = 0;我< array.length;i++)循环不是最好的选择。为什么?如果你有这个:

var array = new Array();
array[1] = "Hello";
array[7] = "World";
array[11] = "!";

The method will call from array[0] to array[2]. First, this will first reference variables you don't even have, second you would not have the variables in the array, and third this will make the code bolder. Look here, it's what I use:

该方法将从数组[0]调用数组[2]。首先,这是第一个引用变量,你甚至没有,第二,你不会有数组中的变量,第三,这会使代码更大胆。看这里,我用的是:

for(var i in array){
    var el = array[i];
    //If you want 'i' to be INT just put parseInt(i)
    //Do something with el
}

And if you want it to be a function, you can do this:

如果你想让它成为一个函数,你可以这样做:

function foreach(array, call){
    for(var i in array){
        call(array[i]);
    }
}

If you want to break, a little more logic:

如果你想休息,多一点逻辑:

function foreach(array, call){
    for(var i in array){
        if(call(array[i]) == false){
            break;
        }
    }
}

Example:

例子:

foreach(array, function(el){
    if(el != "!"){
        console.log(el);
    } else {
        console.log(el+"!!");
    }
});

It returns:

它返回:

//Hello
//World
//!!!

#13


16  

As of ES6:

作为ES6:

 

list = [0, 1, 2, 3]
for (let obj of list) {
    console.log(obj)
}

 

Where of avoids the oddities associated with in and makes it work like the for loop of any other language, and let binds i within the loop as opposed to within the function.

在哪里可以避免与之相关的古怪,使它像其他语言的循环一样工作,并让我在循环中与函数内的函数绑定。

The braces ({}) can be omitted when there is only one command (e.g. in the example above).

当只有一个命令(例如上面的例子)时,可以忽略括号({})。

#14


13  

There isn't any for each loop in native JavaScript. You can either use libraries to get this functionality (I recommend Underscore.js), use a simple for in loop.

本地JavaScript中没有任何for循环。您可以使用库来获得这个功能(我推荐使用Underscore.js),使用一个简单的for循环。

for (var instance in objects) {
   ...
}

However, note that there may be reasons to use an even simpler for loop (see Stack Overflow question Why is using “for…in” with array iteration such a bad idea?)

但是,请注意,可能有理由使用一个更简单的for循环(参见Stack Overflow的问题,为什么使用“for…in”和数组迭代这样一个坏主意?)

var instance;
for (var i=0; i < objects.length; i++) {
    var instance = objects[i];
    ...
}

#15


13  

This is an iterator for NON-sparse list where the index starts at 0, which is the typical scenario when dealing with document.getElementsByTagName or document.querySelectorAll)

这是一个非稀疏列表的迭代器,索引从0开始,这是处理文档时的典型场景。getElementsByTagName或document.querySelectorAll)

function each( fn, data ) {

    if(typeof fn == 'string')
        eval('fn = function(data, i){' + fn + '}');

    for(var i=0, L=this.length; i < L; i++) 
        fn.call( this[i], data, i );   

    return this;
}

Array.prototype.each = each;  

Examples of usage:

使用的例子:

Example #1

示例# 1

var arr = [];
[1, 2, 3].each( function(a){ a.push( this * this}, arr);
arr = [1, 4, 9]

Example #2

例# 2

each.call(document.getElementsByTagName('p'), "this.className = data;",'blue');

Each p tag gets class="blue"

每个p标签得到class="blue"

Example #3

示例# 3

each.call(document.getElementsByTagName('p'), 
    "if( i % 2 == 0) this.className = data;",
    'red'
);

Every other p tag gets class="red">

所有其他的p标签都是class="red">。

Example #4

示例# 4

each.call(document.querySelectorAll('p.blue'), 
    function(newClass, i) {
        if( i < 20 )
            this.className = newClass;
    }, 'green'
);

And finally the first 20 blue p tags are changed to green

最后20个蓝色的p标签变成了绿色。

Caution when using string as function: the function is created out-of-context and ought to be used only where you are certain of variable scoping. Otherwise, better to pass functions where scoping is more intuitive.

在使用字符串作为函数时要谨慎:该函数是在上下文之外创建的,应该只在确定变量范围的地方使用。否则,更好地传递函数,在这个函数中,范围更直观。

#16


12  

There are a few ways to loop through an array in JavaScript, as below:

有几种方法可以在JavaScript中循环,如下所示:

for - it's the most common one. Full block of code for looping

这是最常见的一种。用于循环的完整代码块。

 

var languages = ["JAVA", "JavaScript", "C#", "Python"];
var i, len, text;
for (i = 0, len = languages.length, text = ""; i < len; i++) {
    text += languages[i] + "<br>";
}
document.getElementById("example").innerHTML = text;
<p id="example"></p>

 

while - loop while a condition is through. It seems to be the fastest loop

while循环while一个条件是通过。这似乎是最快的循环。

 

var text = "";
var i = 0;
while (i < 10) {
    text +=  i + ") something<br>";
    i++;
}
document.getElementById("example").innerHTML = text;
<p id="example"></p>

 

do/while - also loop through a block of code while the condition is true, will run at least one time

do/while——在条件为真时,也循环遍历代码块,至少运行一次?

 

var text = ""
var i = 0;
do {
    text += i + ") something <br>";
    i++;
}
while (i < 10);
document.getElementById("example").innerHTML = text;
<p id="example"></p>

 

Functional loops - forEachmapfilter, also reduce (they loop through the function, but used if you need to do something with your array, etc.

功能循环——forEach, map, filter, also reduce(它们通过函数循环,但是如果你需要对数组做一些事情的话,可以使用)。

 

// For example, in this case we loop through the number and double them up using the map function
var numbers = [65, 44, 12, 4];
document.getElementById("example").innerHTML = numbers.map(function(num){return num * 2});
<p id="example"></p>

 

For more information and examples about functional programming on arrays, look at the blog post Functional programming in JavaScript: map, filter and reduce.

有关数组功能编程的更多信息和示例,请查看JavaScript中的博客功能编程:map、filter和reduce。

#17


11  

There's no inbuilt ability to break in forEach. To interrupt execution use the Array#some like below:

没有内在的能力去突破每一个。要中断执行,请使用下面的数组#:

[1,2,3].some(function(number) {
    return number === 1;
});

This works because some returns true as soon as any of the callbacks, executed in array order, returns true, short-circuiting the execution of the rest. Original Answer see Array prototype for some

这是可行的,因为有些回调是正确的,以数组的顺序执行,返回true,使其余的执行短路。原来的答案是一些的数组原型。

#18


11  

ECMAScript5 (the version on Javascript) to work with Arrays.

ECMAScript5 (Javascript的版本)与数组一起工作。

forEach - Iterates through every item in the array and do whatever you need with each item.

forEach——遍历数组中的每一个条目,并对每个条目做任何你需要的事情。

['C', 'D', 'E'].forEach(function(element, index) {
  console.log(element + " is the #" + (index+1) + " in musical scale");
});

// Output
// C is the #1 in musical scale
// D is the #2 in musical scale
// E is the #3 in musical scale

In case , more interested on operation on array using some inbuilt feature.

如果对数组的操作更感兴趣,请使用一些内置的特性。

map - It creates a new array with the result of the callback function. This method is good to be used when you need to format the elements of your array.

map—它使用回调函数的结果创建一个新的数组。当您需要格式化数组元素时,这个方法是很好的。

// Let's upper case the items in the array
['bob', 'joe', 'jen'].map(function(elem) {
  return elem.toUpperCase();
});

// Output: ['BOB', 'JOE', 'JEN']

reduce - As the name says it reduces the array to a single value by calling the given function passing in the currenct element and the result of the previous execution.

reduce——顾名思义,它通过调用在currenct元素中传递的给定函数和之前执行的结果,将数组减少到一个值。

[1,2,3,4].reduce(function(previous, current) {
  return previous + current;
});
// Output: 10
// 1st iteration: previous=1, current=2 => result=3
// 2nd iteration: previous=3, current=3 => result=6
// 3rd iteration: previous=6, current=4 => result=10

every - Returns true or false if all the elements in the array pass the test in the callback function.

如果数组中的所有元素都通过回调函数中的测试,则返回true或false。

// Check if everybody has 18 years old of more.
var ages = [30, 43, 18, 5];  
ages.every(function(elem) {  
  return elem >= 18;
});

// Output: false

filter - Very similar to every except that filter return an array with the elements that return true to the given function.

过滤器——非常类似于每一个过滤器,除了过滤器返回一个数组,其中的元素返回到给定的函数。

// Finding the even numbers
[1,2,3,4,5,6].filter(function(elem){
  return (elem % 2 == 0)
});

// Output: [2,4,6]

Hope this will be useful.

希望这是有用的。

#19


8  

I also would like to add this as a composition of a reverse loop and an answer above for someone that would like this syntax too.

我还想把它添加到一个反向循环的组合中,并在上面给出一个类似于这个语法的答案。

var foo = [object,object,object];
for (var i = foo.length, item; item = foo[--i];) {
    console.log(item);
}

Pros:

优点:

The benefit for this: You have the reference already in the first like that won't need to be declared later with another line. It is handy when looping trough the object array.

这样做的好处是:您已经有了第一个类似的引用,不需要稍后再用另一行来声明。当循环槽的对象数组时,它是很方便的。

Cons:

缺点:

This will break whenever the reference is false - falsey (undefined, etc.). It can be used as an advantage though. However, it would make it a little bit harder to read. And also depending on browser it can be "not" optimized to work faster than original one.

当引用为false - falsey(未定义的等)时,它就会中断。但它也可以作为一种优势。然而,它会使阅读变得更加困难。而且,根据浏览器的不同,它可以“不”优化,比原来的更快。

#20


7  

jQuery way using $.map:

jQuery使用$ . map方式:

var data = [1, 2, 3, 4, 5, 6, 7];

var newData = $.map(data, function(element) {
    if (element % 2 == 0) {
        return element;
    }
});

// newData = [2, 4, 6];

#21


4  

A way closest to your idea would be to use Array.forEach() which accepts a clojure function wich will be executed for each element of the array.

与您的想法最接近的方法是使用Array.forEach(),它接受一个clojure函数,它将为数组的每个元素执行。

myArray.forEach(
  (item) => {
    // do something 
    console.log(item);
  }
);

Another viable way would be to use Array.map() which works in the same way but also mutates each element and returns it like:

另一种可行的方法是使用Array.map(),它以同样的方式工作,但也会对每个元素进行变异,并返回如下:

var myArray = [1, 2, 3];
myArray = myArray.map(
  (item) => {
    return item + 1;
  }
);

console.log(myArray); // [2, 3, 4]

#22


2  

The lambda syntax doesnt usually work in IE 10 or below.

lambda语法通常不会在IE 10或以下工作。

I usually use the

我通常使用

[].forEach.call(function(value,index){
    console.log("value of the looped element" + value);
    console.log("index of the looped element" + index);
});


If you are a jQuery Fan and already have a jQuery file running, you should reverse the positions of the index and value parameters

$("#ul>li").each(function(**index,value**){
    console.log("value of the looped element" + value);
    console.log("index of the looped element" + index);
});

#23


1  

var a = ["car", "bus", "truck"]
a.forEach(function(item, index) {
    console.log("Index" + index);
    console.log("Element" + item);
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值