我有以下内容:
var gridData = {};
var TestRow = {
"name": "xx",
"description": "xx",
"subjectId": 15
};
gridData.push(TestRow)
如何查找新数据的索引号 我刚推入gridData对象?
答案 0 :(得分:54)
首先,我假设gridData
是一个数组,而不是你在示例代码中显示的对象,因为一个对象没有.push()
方法,而是一个数组确实
使用.length - 1
作为推送到数组的最后一项的索引,或者保存.push()
的返回值,这是数组的新长度。这将是您刚刚推送到数组的元素的索引,并且在您在该索引之前修改数组(在该索引之前添加或删除项目)之前,该元素的索引才有效。
var testRowIndex = gridData.push(TestRow) - 1;
// then you can access that item like this
var item = gridData[testRowIndex];
尽管如此,由于您已经在TestRow
中拥有数据,因此这并没有多大意义。像往常一样,如果你描述了你真正试图解决的问题,我们可能会提供更多有用的答案。
答案 1 :(得分:4)
将项目推入数组时,您将获得数组的当前长度作为返回值。用它来查找索引。
var gridData = [];
var TestRow = {
"name": "xx",
"description": "xx",
"subjectId": 15
};
var length=gridData.push(TestRow);
alert(length-1);
Array.push 返回调用该方法的对象的新长度属性。
答案 2 :(得分:1)
首先,我会说它与find-indexof-element-in-jquery-array
类似无论如何,看到@jfriend00
和@PSCoder
精彩地回答它,我想传达一些替代品来寻找指数,
假设您的数组为: -
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>