如果我的IF语句为false,如何让if / else语句运行一堆函数?

时间:2016-10-14 20:42:27

标签: javascript

所以我要做的是创建一个网站,可以将英文字母平均频率的百分比转换为它们在给定消息长度中出现的次数,这是我的代码的一部分那是行不通的。

var Messagelength = prompt("What is the length of a single passage from the broken-up cryptogram? Write down as the numbers appear, or else you will    need to refresh this page and try again.");
if (0 >= Messagelength)(true){
    confirm("No negative numbers or 0 are accepted")};
if (0 >= Messagelength)(false){
var MessagelengthA = function(number) {
    var PercentageA = number * 0.08167;
    confirm(PercentageA);
};
};

我想要它做的是正常运行我的其余脚本,但前提是在代码中看不见的部分提示的数字大于0。 因此,经过几次人们告诉我的事情,我最终决定这是我迈向目标的最佳踏脚石。但问题仍然存在,它不起作用。如果我要删除第二个if语句,第一个播放无论如何,如果我删除第一个或只留下第二个if语句,则没有任何反应,甚至没有发生,甚至没有初始提示确定Messagelength的值是什么。所以回顾一下,我的问题是,如何让页面运行26个不同函数的脚本,但前提是用户在提示中放入的数字大于0,如果不是更大,则不运行这26个函数比0?

编辑:我能找到错误并纠正错误。我的if语句结尾处有一个分号,它不应该在那里。脚本终于以我想要的方式工作了。谢谢!

2 个答案:

答案 0 :(得分:2)

你在问题​​标题中说过了。这是一个if/else语句,因此将其余代码放在else块中。

var MessagelengthA = function(number) {
    var PercentageA = number * 0.08167;
    confirm(PercentageA);
};
if (MessageLength <= 0) {
    alert("No negative numbers or 0 are accepted");
} else {
    MessageLengthA(MessageLength);
    // rest of code here        
}

答案 1 :(得分:1)

删除continue。那是为了重启循环体。

如果给定条件为真,if语句仅提供运行代码的方法。如果是,则运行该代码块。无论是否存在,都会运行以下块。

if (true) {
  console.log('The condition is true so I run');
}
console.log('I run just because I come next in the script');
if (false) {
  console.log('I will never run');
}
console.log('Again, I will run');

因此,您的代码将在if语句后自动运行。你想要的是一种阻止以下代码在某些情况下运行的方法。最简单的方法是使用else

if (true) {
  console.log('true condition, I run');
} else {
  console.log('I do not since the preceding `if` block did');
}

if (false) {
  console.log('I will not run');
} else {
  console.log('since the condition failed, I will run');
}