jquery.each循环多个对象

时间:2016-07-12 14:52:46

标签: jquery

我有两个同时遍历的对象。例如:

var param1= [1,2,3];
var param2= ["a","b","c"];

jQuery.each ((param1,param2), function (key,value){
alert (param1,param2);
}

期望的结果:1a 2b 3c

有没有办法用jQuery.each实现这个目的?或jQuery中的替代。

由于

2 个答案:

答案 0 :(得分:1)

如果将它们更改为数组,可以使用$.each遍历其中一个,然后使用索引访问另一个数组中的相应元素。

var param1 = [1, 2, 3];
var param2 = ['a', 'b', 'c'];
$.each(param1, function(index, value1) {
  var value2 = param2[index];
  console.log(value1 + value2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

答案 1 :(得分:1)

在jQuery.each函数中,第一个参数应该是一个数组,第二个应该是回调, http://api.jquery.com/jquery.each/

您不需要使用jquery每个函数,您可以使用简单的逻辑在纯JavaScript中执行此操作。

var param1= [1,2,3];
var param2= ['a','b','c'];
for(var i=0;i<(param1.length>param2.length?param1.length:param2.length);i++) { 
alert(typeof param1[i]!='undefined'?param1[i]:'');
alert(typeof param2[i]!='undefined'?param2[i]:'');}
相关问题