Home  >  Article  >  Web Front-end  >  JS array iteration method_javascript skills

JS array iteration method_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:15:381229browse

The example in this article describes the array iteration method of JS. Share it with everyone for your reference. The specific implementation method is as follows:

<!doctype html>
<html>
<head lang="zh">
  <meta charset="utf-8">
  <title>js数组迭代</title>
  <meta name="renderer" content="webkit">
  <script>
    var arr1 = [1,2,3,4,5,6];
    function double(x){
      return 2*x;
    }
    // map可以产生一个新的数组
    // alert(arr1.map(double));
    function print(x){
      console.log(x*2)
    }
    arr1.forEach(print);
    function even(x){
      return x %2 ==0
    }
    var arr2 = [2,4,,5,6];
    // alert(arr2.every(even))//false;
    // alert(arr2.some(even))//true;
    function add(a,b){
    return a*b;
    }
    var arr3=[1,2,4,5];
    var factorial = arr3.reduce(add);
    //alert(factorial) //40

    var arr4=[1,24,5,6,7,8,234,4];
    alert(arr4.filter(even))
  </script>
  <pre class="brush:php;toolbar:false">
    map,filter可以产生一个新的数组
    var arr1 = [1,2,3,4,5,6];
    function double(x){
      return 2*x;
    }
   //alert(arr1.map(double));
   //forEach是对数组每项都调用某个函数,不返回
    function print(x){
      console.log(x*2)
    }
    arr1.forEach(print);
   //some,every 参数是一个有返回布尔值的函数
    function even(x){
      return x %2 ==0
    }
    var arr2 = [2,4,,5,6];
    // alert(arr2.every(even))//false;
    // alert(arr2.some(even))//true;
    //reduce接受一个函数,返回一个值 ,不断累加到最后一项
    //同理,reduceRight是由后面累加到第一项,具体可从CONCAT 看出
    function add(a,b){
    return a*b;
    }
    var arr3=[1,2,4,5];
    var factorial = arr3.reduce(add);
    //alert(factorial) //40
    //filter与every类似,参入一个返回布尔值 的函数,返回一个新的数组
  

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn