简体   繁体   English

我可以使用if语句显示数组(JavaScript)中的更改吗?

[英]Can I use an if statement to display the changes in my array (JavaScript)?

I'm trying to make my function displayValues() display each value stored in the array arrValues each time it is called. 我试图让我的功能displayValues()显示存储在阵列中的每个值arrValues每次调用时间。 The array undergoes a change before the second time it is called. 数组在第二次调用之前经历了更改。

I am having trouble making the output text display the starting values in one HTML element, and then the updated values in the second element. 我在使输出text在一个HTML元素中显示起始值,然后在第二个元素中显示更新值时遇到麻烦。 I am not allowed to have the functions return any value. 我不允许这些函数返回任何值。 At the moment my If statement only shows the updated array. 目前,我的If语句仅显示更新后的数组。 I'd like to know what's causing the before element to not be shown? 我想知道是什么导致before元素不显示?

 function start() { var arrValues = [5, 15, 25, 35, 45, 55, 65]; document.getElementById("msg1").innerHTML="Array values before the update:"; displayValues(arrValues); updateValues(arrValues); document.getElementById("msg2").innerHTML="Array values after the update:"; displayValues(arrValues); } function displayValues(dispVals) { var i = 0; var text = ""; var before = document.getElementById("before"); var after = document.getElementById("after"); while (i < dispVals.length) { text += dispVals[i] + " "; i++; } if (before == "") { before.innerHTML=text; } else if (before != "") { after.innerHTML=text; } } function updateValues(upVals) { var i = 0; while (i < upVals.length) { upVals[i] = upVals[i] + 10; i++; } } window.onload = start; 
 <!DOCTYPE html> <html lang="en"><head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <meta name="description" content="Updating array values"> <meta name="keywords" content="arrays, display, update"> <meta name="author" content=""> <title></title> <script src="w8P1.js"></script> </head> <body> <header> <h2>Arrays</h2> </header> <article> <p><span id="msg1"></span> <br /> <span id="before"></span> <br /> <span id="msg2"></span> <br /> <span id="after"></span> </p> </article> <footer><p>Produced by </p></footer> </body></html> 

As most of the HTML elements don't have a value, you should use innerHTML. 由于大多数HTML元素都没有值,因此应使用innerHTML。 Change the below line your code. 更改下面的代码行。

if (before.innerHTML == "") {
        before.innerHTML=text;
    } else if (before != "") {
        after.innerHTML=text;
    }

You set var before = document.getElementById("before"); 您将var before = document.getElementById("before");设置为var before = document.getElementById("before");

So before is the HTML span element, not a string. 因此,HTML span元素而不是字符串。

You should compare the contents of the span: 您应该比较范围的内容:

if(before.innerHTML == ""){...}

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

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