在 Javascript 中一次迭代两个数组
我想同时迭代两个数组,因为数组 A 中任何给定索引 i
的值对应于数组 B 中的值。
我当前正在使用此代码,并获取 当我调用
。alert(queryPredicates[i])
或 alert(queryObjects[i])
时,未定义
当我在调用此函数之前打印出数组时,我知道我的数组已填充。
//queryPredicates[] and queryObjects[] are defined above as global vars - not in a particular function, and I have checked that they contain the correct information.
function getObjectCount(){
var variables = queryPredicates.length; //the number of variables is found by the length of the arrays - they should both be of the same length
var queryString="count="+variables;
for(var i=1; i<=variables;i++){
alert(queryPredicates[i]);
alert(queryObjects[i]);
}
I want to iterate over two arrays at the same time, as the values for any given index i
in array A corresponds to the value in array B.
I am currently using this code, and getting undefined
when I call alert(queryPredicates[i])
or alert(queryObjects[i])
.
I know my array is populated as I print out the array prior to calling this.
//queryPredicates[] and queryObjects[] are defined above as global vars - not in a particular function, and I have checked that they contain the correct information.
function getObjectCount(){
var variables = queryPredicates.length; //the number of variables is found by the length of the arrays - they should both be of the same length
var queryString="count="+variables;
for(var i=1; i<=variables;i++){
alert(queryPredicates[i]);
alert(queryObjects[i]);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
任何数组的
length
属性的值都是元素的实际数量(更准确地说,是最大的现有索引加一)。如果您尝试访问此索引,它将始终为
未定义
,因为它超出了数组的边界(这种情况发生在循环的最后一次迭代中,因为i<=variables
条件)。在 JavaScript 中,索引的处理范围是
0
到length - 1
。除此之外,请确保两个数组具有相同数量的元素。
The value of the
length
property of any array, is the actual number of elements (more exactly, the greatest existing index plus one).If you try to access this index, it will be always
undefined
because it is outside of the bounds of the array (this happens in the last iteration of your loop, because thei<=variables
condition).In JavaScript the indexes are handled from
0
tolength - 1
.Aside of that make sure that your two arrays have the same number of elements.
如果
queryPredicates
没有数字索引,例如 0、1、2 等。那么当第一个项目的索引为queryPredicates['some_index']
不会发出任何警报。尝试使用
for
循环代替:If
queryPredicates
does not have numerical indexes, like 0, 1, 2, etc.. then trying to alert the valuequeryPredicates[0]
when the first item has an index ofqueryPredicates['some_index']
won't alert anything.Try using a
for
loop instead:JS 中的数组是从零开始的。长度是实际计数。您的循环超出了数组的范围。
Arrays in JS are zero based. Length is the actual count. Your loop is going outside the bounds of the array.