JQuery 为每个函数获取数组索引

发布于 2025-01-09 04:47:42 字数 624 浏览 0 评论 0原文

我有一个数组如下:

result = [];
    result.push({label: 'test label 1', value: 'test value 1'});
    result.push({label: 'test label 2', value: 'test value 2'});

    $.each(result, function( key, value ) {
        console.log(key);
        console.log(value.label);
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

我正在尝试使用“console.log(key)”检索数组中项目的索引值,但它总是返回 0。如何在迭代时获取数组中每个项目的索引值?

I have an array as follows:

result = [];
    result.push({label: 'test label 1', value: 'test value 1'});
    result.push({label: 'test label 2', value: 'test value 2'});

    $.each(result, function( key, value ) {
        console.log(key);
        console.log(value.label);
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I'm trying to retrieve the index value of the item in the array using 'console.log(key)' but it always returns 0. How do i get the index value of each item in array as it iterates?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

时间你老了 2025-01-16 04:47:42

如果你想返回每个元素的值,那么你需要编写如下,因为 key 将始终返回元素的当前索引。

result = [];
result.push({label: 'test label 1', value: 'test value 1'});
result.push({label: 'test label 2', value: 'test value 2'});

$.each(result, function( key, value ) {
    console.log(key);
    console.log(value.label);
    console.log(result[key]);
})

If you want to return value of each element then you need to write as below, because key will return always current index of element.

result = [];
result.push({label: 'test label 1', value: 'test value 1'});
result.push({label: 'test label 2', value: 'test value 2'});

$.each(result, function( key, value ) {
    console.log(key);
    console.log(value.label);
    console.log(result[key]);
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文