JS's forEach() method (dynamically obtain data)

Definition and usage

The forEach( ) method is used to call each element of the array and pass the element to the callback function

Note: forEach( ) will not execute the callback function for an empty array.

grammar:

array.forEach(function(currentValue, index, arr), thisValue)

where function(currentValue, index, arr), in

Parameters (currentValue, index, arr) The parameter is mandatory , the function that needs to be called for each element in the array,

thisValue is optional, the value passed to the function is generally "this" value, if this parameter is empty, "undefined" will be passed to the "this" value.

Example:

html code

<ul> </ul>

js code:

var infoList=[
			{name:'one'},
			{name:'two'},
			{name:'throw'},
			{name:'fore'},
			{name:'five'}
		]
		var ul=document.querySelector('ul');
		var st='';
		infoList.forEach(function(item){
			// infoList 内有多少个对象, 执行多少回
			// 有多少对象就需要多少个 ul 标签
			str +='<ul>'
			for(var key in item){
				// 对象内有多少个成员, 执行多少回
				// 有多少成员, 就需要多少个 li 标签
				console.log(item)
				st +='<li>' +item[key]+'</li>'+'<br>'
			}
			st +='</ul>'
		})
ul.innerHTML=st

Console output:

{name: 'one'}
{name: 'two'}
{name: 'throw'}
{name: 'fore'}
{name: 'five'}

The page shows:

This is an example of dynamically rendering ul li data.

There are also several examples on the official website:

Multiply all values ​​in an array by a specific number

<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>

Calculates the sum of all elements of an array

<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>

The resulting totals are added up in turn!

Guess you like

Origin blog.csdn.net/qq_45904018/article/details/126700069