One of the new methods in ES5-array method

New array methods in ES5

Iteration (traversing) method: forEach()、map()、filter()、some()、every();

One, forEach() method

array.forEach(function(currentValue,index,arr))	
  • currentValue: the value of the current item in the array
  • index: the current index of the array
  • arr: the array object itself
 <script>
        // forEach 迭代(遍历)数组
        var arr = [1,2,3]
        var sum = 0;
        arr.forEach(function(value,index,array){
    
    
            console.log('数组元素' + value);
            console.log('索引号' + index);
            console.log('数组的本身' + array);
     
        //它们的和为
            sum = sum + value;
            console.log(sum)
        })

    </script>

Insert picture description here

Two, filter() method

array.filter(function(currentValue,index,arr))	
  • The filter() method creates a new array. The elements in the new array are checked by checking all the elements in the specified array that meet the conditions.主要用于筛选数组
  • 注意它直接返回一个新数组
  • currentValue: the value of the current item in the array
  • index: the current index of the array
  • arr: the array object itself
<script>
        //filter 筛选数组
        var arr = [12,5,21,6,7,8];
       var newArr = arr.filter(function(value,index){
    
    
            // return value>=10;
            return value%2 === 0;

        });
        console.log(newArr);
    </script>

Interview case:利用filter进行数组去重

<script>
	var arr =[1, 2, 3, 1, 2, 4, 'abb', 'abb']
	var newArr = arr.filter(function(item,index,arr){
    
    
		return arr.indexOf(item) === index;
	})
	console.log(newArr)
</script>

Print result

Three, some() method

array.some(function(currentValue,index,arr))	
  • The some() method is used to detect whether the elements in the array meet the specified conditions, and it is popular to find whether there are elements in the array that meet the conditions
  • 注意它返回值是布尔值,如果查找到这个元素,就返回true,如果查找不到就返回false
  • If the first element that satisfies the condition is found, the loop is terminated, and the search is not continued
  • currentValue: the value of the current item in the array
  • index: the current index of the array
  • arr: the array object itself
  //1、some是查找数组中是否存在满足条件的值,如果有返回true  否则就返回false
        var ac = [1,2,3];
        var flag = ac.some(function(value,index){
    
    
            // return value ==2;   存在2这个参数  返回的是true
             return value >=5;   	//不存在这个条件   返回的是false
            
        })
        console.log(flag)
        //2、filter  也是查找满足条件的元素  返回的是一个数组  而且是吧所有满足条件的元素返回回来
        //2、some  也是查找满足条件的元素是否存在  返回的是一个布尔值  如果查找到第一个满足条件的元素就终止循环

Four, map() method

map() 方法返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组。与forEach方法类似

Reference link

Five, every() method

对数组中的每一个元素运行给定的函数,如果数组中每一个元素都能通过回调函数的测试,就会返回true,如果其中有一个元素通过回调函数的测试返回的是false,则返回false;

Reference link

Guess you like

Origin blog.csdn.net/weixin_45054614/article/details/113762136