如果语句在JS中执行时甚至为false [英] If statement executes even when false in JS
问题描述
即使if语句为false,java脚本中的Two-sum程序也会运行。当我在textbox1中输入一系列数字时,在textbox2中输入一个数字。它应该显示来自textbox1的2个数字,等于textbox2。
例如1,2,3,6 in textbox1。
5 in textbox2。
答案应该是2,3。
The Two-sum program in java script runs even when the if statement is false. When I enter a series of number in textbox1, and one number in textbox2. It should display 2 numbers from textbox1 which equals to textbox2.
For eg 1,2,3,6 in textbox1.
5 in textbox2.
The answer should be 2,3.
function TwoSum() {
inputArray1 = document.getElementById("inputText1").value.split(",");
inputArray2 = document.getElementById("inputText2").value.split(",");
var two = [];
var sum = 0;
var y = 0;
y = inputArray2[0];
var z = 0;
var a = 0; //input array 1
var b = 0; //input array 2
for (i = 0; i < inputArray1.length - 1; i++) {
if (z == 0) {
for (j = inputArray1.length - 1; j >= i; j--) {
//if (inputArray1[i] + inputArray1[j] == y)
a = inputArray1[i];
b = inputArray1[j];
if (a + b == y)
{
two[sum] = inputArray1[i];
sum++;
two[sum] = inputArray1[j];
sum++;
z++;
break;
}
}
}
if (z > 0)
break;
else
var incorrect = false;
}
if (z > 0)
document.getElementById("result").value = two.join(",");
else
document.getElementById("result").value = incorrect;
}
我的尝试:
当我在1个textBox中输入2,4,5,3而在第2个文本框中输入5时,答案应该在第一个循环中打印2,3。但是当我调试时,if(a + b == y)没有被执行。它无论如何都会读为false并跳回到= inputArray1 [i],b = inputArray2 [i]。
What I have tried:
When I enter 2,4,5,3 in 1 textBox and 5 in 2nd textbox, the answer should print 2,3 in the first loop itself. But when I debug, the if(a+b==y) isn't getting executed. It reads as false no matter what and jumps back to a=inputArray1[i], b= inputArray2[i].
推荐答案
因为所有数字都在字符串中格式。因此2 + 3实际上被评估为字符串23,而不是算术和5.您首先需要将字符转换为实际数值。请参阅 JavaScript parseInt()函数 [ ^ ]。
Because all your numbers are in character string format. So 2 + 3 is actually evaluated as the string 23, not the arithmetic sum 5. You first need to convert your characters into actual numeric values. See JavaScript parseInt() Function[^].
这篇关于如果语句在JS中执行时甚至为false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!