Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

javascript - 在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.

(其中theArray是我的数组,但这似乎是不正确的。)

  ask by Dante1986 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

TL;DR

(TL; DR)

  • Don't use for-in unless you use it with safeguards or are at least aware of why it might bite you.

    (除非您将for-in防护措施,否则至少不要知道为什么它会咬您。)

  • Your best bets are usually

    (通常最好的选择是)

    • a for-of loop (ES2015+ only),

      (for-of循环(仅for-of ES2015 +),)

    • Array#forEach ( spec | MDN ) (or its relatives some and such) (ES5+ only),

      (Array#forEachspec | MDN )(或其some类似的亲戚)(仅适用于ES5 +),)

    • a simple old-fashioned for loop,

      (一个简单的老式for循环,)

    • or for-in with safeguards.

      (或者for-in有保障。)

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

(但是,还有其它更多探索,阅读...)


JavaScript has powerful semantics for looping through arrays and array-like objects.

(JavaScript具有强大的语义,可以遍历数组和类似数组的对象。)

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.

(我将答案分为两部分:真正数组的选项,以及仅是数组之类的东西的选项,例如arguments对象,其他可迭代对象(ES2015 +),DOM集合,等等。)

I'll quickly note that you can use the ES2015 options now , even on ES5 engines, by transpiling ES2015 to ES5.

(我会很快注意到,您现在可以通过将ES2015转换为ES5,甚至在ES5引擎上使用ES2015选项。)

Search for "ES2015 transpiling" / "ES6 transpiling" for more...

(搜索“ ES2015 transpiling” /“ ES6 transpiling”以了解更多...)

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 two more added in ECMAScript 2015 ("ES2015", "ES6"):

(您目前在ECMAScript 5 (“ ES5”)中拥有三个选项,这是目前最广泛支持的版本,在ECMAScript 2015中又添加了两个选项(“ ES2015”,“ ES6”):)

  1. Use forEach and related (ES5+)

    (适用于forEach及相关(ES5 +))

  2. Use a simple for loop

    (使用简单的for循环)

  3. Use for-in correctly

    (正确使用for-in)

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

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

  5. Use an iterator explicitly (ES2015+)

    (明确使用迭代器(ES2015 +))

Details:

(细节:)

1. Use forEach and related(1.使用forEach及相关)

In any vaguely-modern environment (so, not IE8) where you have access to the Array features added by ES5 (directly or using polyfills), you can use forEach ( spec | MDN ):

(在任何可以访问由ES5添加的Array功能(直接或使用polyfills)的模糊现代环境(因此,不是IE8)中,都可以使用forEachspec | MDN ):)

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

forEach accepts a callback function and, optionally, a value to use as this when calling that callback (not used above).

(forEach接受一个回调函数,以及(可选)一个在调用该回调时用作this函数的值(上面未使用)。)

The callback 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 callback 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).

(尽管我在上面只使用了一个参数,但回调函数使用以下三个参数调用:每个条目的值,该条目的索引以及对要迭代的数组的引用(以防您的函数尚未使用它) )。)

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.

(除非您支持IE8之类的过时浏览器(截至2016年9月,NetApps在市场中所占份额刚刚超过4%),否则您可以在通用网页中愉快地使用forEach ,而无需填充。)

If you do need to support obsolete browsers, shimming/polyfilling forEach is easily done (search for "es5 shim" for several options).

(如果您确实需要支持陈旧的浏览器,则可以轻松完成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 callback returns false or something falsey)

    (every (在回调第一次返回falsefalse时停止循环))

  • some (stops looping the first time the callback returns true or something truthy)

    (some (在回调第一次返回truetrue时停止循环))

  • filter (creates a new array including elements where the filter function returns true and omitting the ones where it returns false )

    (filter (创建一个新数组,其中包含filter函数返回true元素,并忽略其中返回false元素))

  • map (creates a new array from the values returned by the callback)

    (map (根据回调返回的值创建一个新数组))

  • reduce (builds up a value by repeatedly calling the callback, 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)

    (reduceRight (类似于reduce ,但是以降序而不是升序工作))

2. Use a simple for loop(2.使用简单的for循环)

Sometimes the old ways are the best:

(有时,旧方法是最好的:)

<div class="snippet" data-lang="js" data-hi


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...