js片段

it2024-12-17  46

<html> <heard> <script> var add = [2,3,4,5]; var sum = 0; var foreachRes = add.forEach(function(currentValue,index,arr){ console.log("currentValue: "+currentValue); console.log("index: "+index); console.log("arr: "+arr); sum+=currentValue console.log("----:"+this) },100); console.log("sum: "+sum); console.log("foreachRes: "+foreachRes); </script> </heard> <body> </body> </html>

运行结果是:

currentValue: 2 tt.html:9 index: 0 tt.html:10 arr: 2,3,4,5 tt.html:13 ----:100 tt.html:8 currentValue: 3 tt.html:9 index: 1 tt.html:10 arr: 2,3,4,5 tt.html:13 ----:100 tt.html:8 currentValue: 4 tt.html:9 index: 2 tt.html:10 arr: 2,3,4,5 tt.html:13 ----:100 tt.html:8 currentValue: 5 tt.html:9 index: 3 tt.html:10 arr: 2,3,4,5 tt.html:13 ----:100 tt.html:15 sum: 14 tt.html:16 foreachRes: undefined

 

这里边把this设置成100,你设置的是555,已经起到了效果。

undefined的出现是因为 foreach无返回值导致。

转载于:https://www.cnblogs.com/shenbo-/p/8854802.html

相关资源:30secondsofcode中文版翻译收集有用的Javascript片段你可以在30秒或更少的时间里理解
最新回复(0)