zoukankan      html  css  js  c++  java
  • forEach()方法

    一、定义和用法

    forEach( )方法用于调用数组的每个元素,并将元素传递给回调函数。

    二、注意

    forEach( )方法对空数组是不会执行回调函数的。

    三、语法

    array.forEach(function(currentValue,index,arr),this.Value)

    四、参数

    参数描述
    function(currentValue, index, arr) 必需。 数组中每个元素需要调用的函数。
    函数参数:
    参数描述
    currentValue 必需。当前元素
    index 可选。当前元素的索引值。
    arr 可选。当前元素所属的数组对象。
    thisValue 可选。传递给函数的值一般用 "this" 值。
    如果这个参数为空, "undefined" 会传递给 "this" 值

    五、demo
    1.列出数组的每个元素:

    <button onclick="numbers.forEach(myFunction)">点我</button>
    <p id="demo"></p>
    <script>
    demoP = document.getElementById("demo");
    var numbers = [4, 9, 16, 25];
     
    function myFunction(item, index) {
        demoP.innerHTML = demoP.innerHTML + "index[" + index + "]: " + item + "<br>"; 
    }
    </script>
    输出结果:
    index[0]: 4 index[1]: 9 index[2]: 16 index[3]: 25

    2.计算数组所有元素相加的总和:

    <button onclick="numbers.forEach(myFunction)">点我</button>
     
    <p>数组元素总和:<span id="demo"></span></p>
    <script>
    var sum = 0;
    var numbers = [65, 44, 12, 4];
     
    function myFunction(item) {
        sum += item;
        demo.innerHTML = sum;
    }
    </script>
    输出结构:
    125

    3.将数组中的所有值乘以特定数字:

    <p>乘以: <input type="number" id="multiplyWith" value="10"></p>
    <button onclick="numbers.forEach(myFunction)">点我</button>
     
    <p>计算后的值: <span id="demo"></span></p>
    <script>
    var numbers = [65, 44, 12, 4];
     
    function myFunction(item,index,arr) {
        arr[index] = item * document.getElementById("multiplyWith").value;
        demo.innerHTML = numbers;
    }
    </script>
    输出结果:
    650, 440, 120, 40
  • 相关阅读:
    (七)四种常见的post请求中的参数形式
    (六)获取http状态码和处理返回结果
    (五)application/x-www-form-urlencoded(表单请求)
    (四)进行HTTPS请求并进行(或不进行)证书校验(示例)
    (三)解决httpclient乱码
    (二)HttpClient Post请求
    (一)HttpClient Get请求
    (十一)Maven之profile实现多环境配置动态切换
    (四)带图片和附件的复杂邮件发送
    (三)JavaMail发送附件
  • 原文地址:https://www.cnblogs.com/jiunie/p/8599683.html
Copyright © 2011-2022 走看看