测试ForOf会不会多次调用函数2208082050

57 阅读1分钟

测试ForOf会不会多次调用函数2208082050

比如 for(let a of getArray()) 的 getArray()方法会不会多次执行

测试代码

<!DOCTYPE html><head></head><body><script>{
	
	
	let invokedCount = 0;
	let v = 1;
	function getArray(){
		invokedCount+=1;
		let str = "getArray()函数被第 "+invokedCount+" 次调用";
		confirm(str);
		console.log(str);
		return [ v++ , v++ , v++ , v++ , v++ , v++ ];
	}

	for(let a of getArray()){
		var div = document.createElement("div");
		div.innerHTML=a;
		document.body.appendChild(div);
		
		console.log(a);
	}



}</script></body>


结果 在这里插入图片描述

getArray()函数只执行了一次 , 说明for..of 可以直接把函数写在 of 后面, 不用另外定义变量