在JavaScript中,使用each()方法可以遍历数组或对象。each()方法接受一个函数作为参数,该函数将被应用到每个元素上,并将当前元素和索引作为参数传递给该函数。
使用each()方法遍历数组
var arr = [1,2,3,4,5]; arr.each(function(element,index){ console.log(element+' : '+index); });
输出结果为:
1 : 0 2 : 1 3 : 2 4 : 3 5 : 4
使用each()方法遍历对象
var obj = { name: 'John', age: 25, gender: 'male' }; Object.each(obj,function(value,key){ console.log(key+' : '+value); });
输出结果为:
name : John age : 25 gender : male
以上是使用each()方法遍历数组和对象的示例,each()方法是一种快捷的方法,可以简化循环遍历的代码,提高程序的效率。