JQuery 为每个函数获取数组索引
我有一个数组如下:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果你想返回每个元素的值,那么你需要编写如下,因为 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.