js中的forEach与jq中each在遍历方式上的区别
1、forEach
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
forEach()的回调函数有三个参数,index,value,arr,index为当前元素的索引值,value为当前元素,arr为当前数组。
在ajax连接接口时,接口中的数据是数组方式存储的,可以用forEach遍历需要的数据:
其中dataType是jsonp;
forEach前面必须衔接的是数组
$(function () {
$('#btn1').click(function () {
var api =
'https://api.search.mi.com/select?jsonpcallback=jQuery1113036574031971716425_1582209837066&page_index=0&page_size=10'
$.ajax({
type: 'get',
url: api,
dataType: 'jsonp',
success: function (result) {
result.data.items.forEach(function (value, index, arr) {
console.log(value);
})
}
})
})
})
console.log(value);
console.log(index);
console.log(arr);
2、each()方法分两种情况,$().each() 和 $.each()。与forEach不同的是each回调函数中的参数有两个,且第一个是index索引值,第二个是value当前值
(1)$().each()是对页面元素的操作,此时可获取DOM元素直接操作
<ul id="each">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
<button id="click">点击</button>
$(function () {
$('#click').click(function () {
$('#each li').each(function (index, value) {
console.log(index, value);
})
})
})
代码演示:
(2)遍历数组
在上面forEach方法遍历ajax对象也可以用each来实现
$(function () {
$('#btn1').click(function () {
var api =
'https://api.search.mi.com/select?jsonpcallback=jQuery1113036574031971716425_1582209837066&page_index=0&page_size=10'
$.ajax({
type: 'get',
url: api,
dataType: 'jsonp',
success: function (result) {
$res = result.data.items;
console.log($res);
$.each($res, function (index, item) {
console.log(item);
})
}
})
})
})
其中将数组对象赋值给$res
$.each(arr数组,function(index,value);
上面例子中;
console.log($res);
console.log(index);
console.log(item);
输出到页面:
$('#jd').append('<h1>'+item.word+'</h1>');
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果