首先,我会说它类似于find-indexof-element-in-jquery-array
无论如何,看到@jfriend00
并@PSCoder
出色地回答了它,我想向 Find Index 传达一些替代方案,
假设,您的数组为:-
var gridData = [];//{} Curly braces will define it as object type, push operations can take place with respect to Array's
我有两个或更多的数据Array
var TestRow = {
"name": "xx",
"description": "xx",
"subjectId": 15
};
var TestRow1 = {
"name": "xx1",
"description": "xx1",
"subjectId": 151
};
现在,我推送这两个数据,就像你所做的那样。要找到被推送元素的索引,我们可以使用,.indexOf
和.inArray
var indexOfTestRow0 = gridData.indexOf(TestRow);// it returns the index of the element if it exists, and -1 if it doesn't.
var indexOfTestRow1 = gridData.indexOf(TestRow1);// it returns the index of the element if it exists, and -1 if it doesn't.
//Search for a specified value within an array and return its index (or -1 if not found).
var indx1 = jQuery.inArray(TestRow, gridData);
var indx2 = jQuery.inArray(TestRow1, gridData);
考虑测试这些东西,所以我尝试了一些非常简单的方法,如下所示: -
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<script>
$(document).ready(function () {
var gridData = [];//{} Curly braces will define it as Boject type, push operations can take place with respect to Array's
var TestRow = {
"name": "xx",
"description": "xx",
"subjectId": 15
};
var TestRow1 = {
"name": "xx1",
"description": "xx1",
"subjectId": 151
};
gridData.push(TestRow);
gridData.push(TestRow1);
console.log(gridData);
var indexOfTestRow0 = gridData.indexOf(TestRow);// it returns the index of the element if it exists, and -1 if it doesn't.
var indexOfTestRow1 = gridData.indexOf(TestRow1);// it returns the index of the element if it exists, and -1 if it doesn't.
//Search for a specified value within an array and return its index (or -1 if not found).
var indx1 = jQuery.inArray(TestRow, gridData);
var indx2 = jQuery.inArray(TestRow1, gridData);
console.log(indexOfTestRow0);
console.log(indexOfTestRow1);
console.log(indx1);
console.log(indx2);
});
</script>