简体   繁体   English

无法理解为什么我的JS无法正常工作

[英]Having trouble understanding why my JS isnt working

Nothing is happening for me when I run this code. 当我运行此代码时,对我来说什么都没有发生。

var myarray = [2,2,2];

for ( var i = 0 ; i < myarray.length ; i++ ) {
  total = total + myarray[i];
}
alert("The total is " + total);

Try defining total outside of the loop first. 尝试首先在循环外定义合计。

var myarray = [2, 2, 2];
var total = 0;
for (var i = 0; i < myarray.length; i++) {
  total += myarray[i];
}
alert(`The total is ${total}!`);

Something was happening, but you likely couldn't see it. 发生了什么,但您可能看不到。 Try to open the developer console in your browser if you're using one to run this, you'll see the error being generated. 如果您使用浏览器打开开发者控制台,请尝试在其中打开它,您将看到正在生成的错误。

Just declare your variable and initialise it: 只需声明您的变量并将其初始化:

var total =0;
for ( var i = 0 ; i < myarray.length ; i++ ) {
  total = total + myarray[i];
}
alert("The total is " + total);

A nice way to solve it is using reduce as below, cheers! 解决这个问题的一种好方法是使用reduce,加油! ;) ;)

 var arr = [1, 2, 3]; var total = arr.reduce((acum, current) => acum + current); console.log(total); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM