一、jQuery对象遍历
1 <script type="text/javascript" src="js/jquery-3.4.1.js"></script> 2 <script> 3 var cities = ["深圳市","广州市","珠海市","上海市","北京市"]; 4 //jQuery对象调用遍历 5 $(cities).each(function(i,n) { 6 console.log(i+" = "+n); 7 }); 8 </script>
二、jQuery函数调用
1 <script> 2 //jQuery函数调用 3 $.each(cities,function(i,n) { 4 console.log(i+" > "+n); 5 }); 6 </script>
三、纯JavaScript实现
1 <script> 2 var cities = ["深圳市","广州市","珠海市","上海市","北京市"] 3 4 function callback(i,n) { 5 console.log("123:" + i + n); 6 } 7 8 function foreach(array,callback) { 9 for (var i = 0; i < array.length; i++) { 10 var item = array[i]; 11 callback(i,item); 12 } 13 } 14 //调用 15 foreach(cities,callback); 16 </script>
效果
参考链接:https://blog.csdn.net/Woo_home/article/details/91375539