获取稀疏 JavaScript 数组的第一个元素
我有一个 JavaScript 对象数组。我用jquery。
如何获取数组中的第一个元素?我无法使用数组索引 - 因为我在将对象添加到数组时分配每个元素索引。所以索引不是 0、1、2 等。
只需要获取数组的第一个元素?
I have an array of objects in javascript. I use jquery.
How do i get the first element in the array? I cant use the array index - as I assign each elements index when I am adding the objects to the array. So the indexes arent 0, 1, 2 etc.
Just need to get the first element of the array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果您不使用按顺序编号的元素,则必须循环直到遇到第一个元素:
或一些相当愚蠢的结构。这将为您提供第一个项目的索引,您可能会或可能不关心它。
如果这是您需要经常执行的操作,则应该保留对当前第一个有效索引的后备引用,因此这将成为 O(1) 操作,而不是每次 O(n) 操作。如果您经常需要迭代真正稀疏的数组,请考虑另一种数据结构,例如在其旁边保留一个对象,将序数结果反向映射到索引或适合您的数据的东西。
If you don't use sequentially numbered elements, you'll have to loop through until you hit the first one:
or some equivalently silly construction. This gets you the first item's index, which you might or might not care about it.
If this is something you need to do often, you should keep a lookaside reference to the current first valid index, so this becomes an O(1) operation instead of O(n) every time. If you're frequently needing to iterate through a truly sparse array, consider another data structure, like keeping an object alongside it that back-maps ordinal results to indexes, or something that fits your data.
filter
方法适用于稀疏数组。The
filter
method works with sparse arrays.您是否考虑过:
?
作为获取数组中最后元素的一种方法:
这些都没有使用jquery。
Have you considered:
?
And as a way to get the last element in the array:
Neither of these uses jquery.
Object.keys(array)[0]
返回稀疏数组中第一个元素的索引(以String
形式)。Object.keys(array)[0]
returns the index (inString
form) of the first element in the sparse array.我也面临着类似的问题,令人惊讶的是没有人考虑以下问题:
如果需要的话,上面将产生
如果需要的话,您可以在第一次迭代后存在,但通常我们需要知道数组中的哪里开始。
I was also facing a similar problem and was surprised that no one has considered the following:
The above will produce
If needed you could exist after the first iteration if all that was required but generally we need to know where in the array to begin.
这是一个使用 ES5 方法的提案
数组#some
。该代码获取第一个非稀疏元素和索引。迭代立即停止并在回调中返回
true
:This is a proposal with ES5 method with
Array#some
.The code gets the first nonsparse element and the index. The iteration stops immediately with returning
true
in the callback:如果您发现自己需要经常操作数组,您可能会对 Underscore 库感兴趣。它提供了用于操作数组的实用方法,例如 compact:
但是,它听起来确实像你当你构建数组时,你正在做一些奇怪的事情。也许 Array.push 会帮助你?
If you find yourself needing to do manipulation of arrays a lot, you might be interested in the Underscore library. It provides utility methods for manipulating arrays, for example compact:
However, it does sound like you are doing something strange when you are constructing your array. Perhaps Array.push would help you out?