获取稀疏 JavaScript 数组的第一个元素

发布于 2024-09-15 16:35:13 字数 132 浏览 15 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

梦与时光遇 2024-09-22 16:35:13

如果您不使用按顺序编号的元素,则必须循环直到遇到第一个元素:

var firstIndex = 0;
while (firstIndex < myarray.length && myarray[firstIndex] === undefined) {
    firstIndex++;
}
if (firstIndex < myarray.length) {
    var firstElement = myarray[firstIndex];
} else {
    // no elements.
}

或一些相当愚蠢的结构。这将为您提供第一个项目的索引,您可能会或可能不关心它。

如果这是您需要经常执行的操作,则应该保留对当前第一个有效索引的后备引用,因此这将成为 O(1) 操作,而不是每次 O(n) 操作。如果您经常需要迭代真正稀疏的数组,请考虑另一种数据结构,例如在其旁边保留一个对象,将序数结果反向映射到索引或适合您的数据的东西。

If you don't use sequentially numbered elements, you'll have to loop through until you hit the first one:

var firstIndex = 0;
while (firstIndex < myarray.length && myarray[firstIndex] === undefined) {
    firstIndex++;
}
if (firstIndex < myarray.length) {
    var firstElement = myarray[firstIndex];
} else {
    // no elements.
}

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.

俯瞰星空 2024-09-22 16:35:13

filter 方法适用于稀疏数组。

var first = array.filter(x => true)[0];

The filter method works with sparse arrays.

var first = array.filter(x => true)[0];
喜你已久 2024-09-22 16:35:13

您是否考虑过:

function getFirstIndex(array){
    var result;
    if(array instanceof Array){
        for(var i in array){
            result = i;
            break;
        }
    } else {
        return null;
    }
    return result;
}

作为获取数组中最后元素的一种方法:

function getLastIndex(array){
    var result;
    if(array instanceof Array){
            result = array.push("");
            array.pop;
        }
    } else {
        return null;
    }
    return result;
}

这些都没有使用jquery。

Have you considered:

function getFirstIndex(array){
    var result;
    if(array instanceof Array){
        for(var i in array){
            result = i;
            break;
        }
    } else {
        return null;
    }
    return result;
}

?

And as a way to get the last element in the array:

function getLastIndex(array){
    var result;
    if(array instanceof Array){
            result = array.push("");
            array.pop;
        }
    } else {
        return null;
    }
    return result;
}

Neither of these uses jquery.

↙温凉少女 2024-09-22 16:35:13

Object.keys(array)[0] 返回稀疏数组中第一个元素的索引(以String 形式)。

var array = [];
array[2] = true;
array[5] = undefined;

var keys = Object.keys(array);            // => ["2", "5"]
var first = Number(keys[0]);              // => 2
var last = Number(keys[keys.length - 1]); // => 5

Object.keys(array)[0] returns the index (in String form) of the first element in the sparse array.

var array = [];
array[2] = true;
array[5] = undefined;

var keys = Object.keys(array);            // => ["2", "5"]
var first = Number(keys[0]);              // => 2
var last = Number(keys[keys.length - 1]); // => 5
懒猫 2024-09-22 16:35:13

我也面临着类似的问题,令人惊讶的是没有人考虑以下问题:

 var testArray = [];
 testArray [1245]= 31;
 testArray[2045] = 45;
 for(index in testArray){
    console.log(index+','+testArray[index])
 }

如果需要的话,上面将产生

1245,31
2045,45

如果需要的话,您可以在第一次迭代后存在,但通常我们需要知道数组中的哪里开始。

I was also facing a similar problem and was surprised that no one has considered the following:

 var testArray = [];
 testArray [1245]= 31;
 testArray[2045] = 45;
 for(index in testArray){
    console.log(index+','+testArray[index])
 }

The above will produce

1245,31
2045,45

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.

z祗昰~ 2024-09-22 16:35:13

这是一个使用 ES5 方法的提案 数组#some

该代码获取第一个非稀疏元素和索引。迭代立即停止并在回调中返回 true

var a = [, , 22, 33],
    value,
    index;

a.some(function (v, i) {
    value = v;
    index = i;
    return true;
});

console.log(index, value);

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:

var a = [, , 22, 33],
    value,
    index;

a.some(function (v, i) {
    value = v;
    index = i;
    return true;
});

console.log(index, value);

丑疤怪 2024-09-22 16:35:13

如果您发现自己需要经常操作数组,您可能会对 Underscore 库感兴趣。它提供了用于操作数组的实用方法,例如 compact

var yourArray = [];
yourArray[10] = "foo";
var firstValue = _.compact(yourArray)[0];

但是,它听起来确实像你当你构建数组时,你正在做一些奇怪的事情。也许 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:

var yourArray = [];
yourArray[10] = "foo";
var firstValue = _.compact(yourArray)[0];

However, it does sound like you are doing something strange when you are constructing your array. Perhaps Array.push would help you out?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文