ES5 new method (1)


foreword

Today I would like to share with you some new methods in ES5.

1. Array method

Iteration (traversal) methods: forEach(), map(), filter(), some(), every()
array.forEach(function(value,index,arr))
value: the value of the current item in the array
index: the current item in the array index of
arr: the array object itself

2. forEach iterates (traverses) the array

var arr=[1,2,3,4,5];
var num = '';
	arr.forEach(function(value,index,array){
    
    
		console.log('每个元素'+value);
		console.log('每个元素的索引号'+index);
		console.log('数组本身'+array);
		num+=value;
	});
console.log(num);

2. filter()

array.filter(function(value,index,arr));
The filter() method creates a new array, and the elements in the new array are checked by checking all the elements in the specified array that meet the conditions, which is mainly used to filter the array.
It should be noted that it directly returns a new array
value: the value of the current item in the array
index: the index of the current item in the array
arr: the array object itself

filter filter array

var arr=[12,15,18,4,9,37];
var numArr=arr.filter(function(value,index){
    
    
	// return value>=15;
	return value%2===0;
});
console.log(numArr);

3.some()

The some() method is used to detect whether the elements in the array meet the specified conditions. The popular point is to find whether there are elements in the array that meet the conditions.
array.some(function(value,index,arr))
Note that its return value is a boolean value, if the element is found, it will return true, if it cannot find it, it will return false.
If the first element that satisfies the condition is found, the loop is terminated and the search is not continued.

some finds whether there is an element in the array that satisfies the condition

var arr=[10,40,5,9];
			var num=arr.some(function(value){
    
    
				// return value>=30;
				return value<4;
			});
			console.log(num);
var arr=['zhang','wang','sun'];
			var num=arr.some(function(value){
    
    
				return value=='sun';
			});
			console.log(num);

Summarize

  1. filter also finds the elements that meet the conditions and returns an array and returns all the elements that meet the conditions.
  2. some also searches for the existence of elements that meet the conditions, and returns a Boolean value. If the first element that meets the conditions is found, the loop is terminated.

The above is the whole content of this chapter, thank you for reading.

おすすめ

転載: blog.csdn.net/SqlloveSyn/article/details/129855913