在Array.forEach中访问未命名数组

5

在使用forEach循环遍历未命名数组时,有没有办法访问目标对象的length属性?

# I'd like to be able to do something like:
[1, 2, 3].forEach (n, i) -> console.log n is < (arr.length - 1)

好的,这是一个常量数组,所以你“知道”它的长度。在这个例子中,它是3。你需要它做什么? - daniel kullmann
3
@daniel kullmann,这个问题也适用于像getSomething().forEach...这样的代码。 - Arnaud Le Blanc
1个回答

6

Array.forEach 的回调函数接受三个参数:值、索引和被遍历的数组。

因此,你可以这样做:

[1, 2, 3].forEach (n, i, thearray) -> console.log n is < (thearray.length - 1)

Javascript:

[1, 2, 3].forEach(function(n, i, thearray) {
    console.log(n < thearray.length - 1);
});

1
自己注意:RTFM! - pdoherty926

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接