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);
202106251624588548549388

console.log(index);
202106251624588573100787

console.log(arr);
202106251624588632721747

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);
    })
  })
})

代码演示:

202106251624589148665190

(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);
202106251624589678140994

console.log(index);
202106251624589706141950

console.log(item);

202106251624589782142783

输出到页面:

$('#jd').append('<h1>'+item.word+'</h1>');

202106251624589894131465