javascript - 查找对象数组内对象的索引

标签 javascript jquery arrays loops

我有一个从 HTML 项目列表生成的对象数组,在处理数组以获取项目索引和数组长度时遇到问题,总是为零。

我想要数据 ID 和值(列表 1,2,3 ..)。

HTML 代码

<ul class="list">
    <li data-id="l1">list 1</li>
    <li data-id="l2">list 2</li>
    <li data-id="l3">list 3</li>
    <li data-id="l4">list 4</li>
</ul>
<p></p>

JS代码

var arr = new Array();

$('.list li').each(function(){
    var lid = $(this).attr('data-id');
    var lval = $(this).html();
    arr[lid] = lval;
});

$('p').html('array length = ' + arr.length + ' & index of list 1 is ' + arr.indexOf('l1'));

我是 javascript 和 jQuery 的新手,我不知道语法是否有错误。看看这个fiddle

最佳答案

尝试使用arr.push(lval);代替:

您尝试使用 l1 作为要添加数据的索引,但 l1 是字符串,索引必须是数字。 .push() 将添加给定元素作为给定数组中的最后一个元素,可能更多是您正在寻找的内容。

由于您需要 data-id 和元素的 html,因此可以通过执行 arr.push( [lid, lval] )< 创建一个多维数组

var arr = new Array();

$('.list li').each(function(){
    var lid = $(this).attr('data-id');
    var lval = $(this).html();
    arr.push( [lid, lval] );
});

$('p').html('array length = ' + arr.length + ' & index of list 1 is ' + getIndexOfK(arr, 'l1'));


// access values like 
for(var i = 0; i < arr.length; i++){
  
  $('#myDiv').append( 'this element\'s data-id= '+ arr[i][0] +'------ this element\'s html= ' + arr[i][1]+'<br>' );
}






// function to get index of given element in a multidemensional array
// you may not actually need this, it was jsut to get your idex 
// credit: http://stackoverflow.com/questions/16102263/to-find-index-of-multidimensional-array-in-javascript
function getIndexOfK(arr, k){
    for(var i=0; i<arr.length; i++){
        var index = arr[i].indexOf(k);
        if (index > -1){
            return [i, index];
        }
    }
    return -1;
}
#myDiv{
  margin-top:50px;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul class="list">
    <li data-id="l1">list 1</li>
    <li data-id="l2">list 2</li>
    <li data-id="l3">list 3</li>
    <li data-id="l4">list 4</li>
</ul>
<p></p>

<div id="myDiv"></div>

关于javascript - 查找对象数组内对象的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27874728/

相关文章:

c++ - 从 TCP 客户端发送的双数组

python - 如果发现重复项,则取列表中值的平均值

java - java中填充数组

javascript - jQuery 自动完成接受特殊字符的匹配

javascript - 如何使用 jQuery .live() 和 ajax

php - 为动态添加的内容注册事件处理程序

jquery - 由 javascript 创建的 css 动画

javascript - 从客户端向服务器发送伪造的 socket.io 请求(node.js/socket.io)

javascript - 错误: status[x] is undefined

jQuery 单击单元格更改为文本框