嵌套if的javascript问题

javascript trouble with nested if

本文关键字:问题 javascript if 嵌套      更新时间:2023-11-26

我正在尝试输入字符串查询,并从中使用string.match来挑选执行度量转换所需的信息。经过大量的实验,我不断地将其作为输出:"零厘米中有0英寸"

我想知道我if语句中的逻辑是否有问题。下面是一个例子:

    var metric = string.match(/centimeters|liters|grams/);
    var english = string.match(/inches|quarts|pounds/);
    var ind = string.indexOf(metric);
    var ind2 = string.indexOf(english);
   if (string.match(/centimeters/) && string.match(/inches/)){
        if (ind < ind2) {
            var string = document.getElementById("box1").value;
            var num = string.match(/'d+$/);
            parseInt(num);
            var conNum = num * 2.54;
            document.getElementById("unit").innerHTML = "There are " + conNum +  " centimeters in " + num + " inches.";
        }
        if (ind2 < ind) {
            var string = document.getElementById("box1").value;
            var num = string.match(/'d+$/);
            parseInt(num);
            var conNum = num/2.54;
            document.getElementById("unit").innerHTML = "There are " +           conNum +  " inches in " + num + " centimeters.";
            }

我实际上并不能100%确定你想要什么,你还没有告诉最初的string来自哪里,所以我假设一些东西:

HTML

<input type="text" id="box1" value="10" />
<div id="unit"></div>

JAVASCRIPT

    var string = 'centimeters to inches'
    var metric = string.match(/centimeters|liters|grams/);
    var english = string.match(/inches|quarts|pounds/);
    var ind = string.indexOf(metric);
    var ind2 = string.indexOf(english);
   if (string.match(/centimeters/) && string.match(/inches/)){
        if (ind < ind2) {
            var string = document.getElementById("box1").value;
            var num = string.match(/'d+$/);
            parseInt(num);
            var conNum = num * 2.54;
            document.getElementById("unit").innerHTML = "There are " + conNum +  " centimeters in " + num + " inches.";
        }
        if (ind2 < ind) {
            var string = document.getElementById("box1").value;
            var num = string.match(/'d+$/);
            parseInt(num);
            var conNum = num/2.54;
            document.getElementById("unit").innerHTML = "There are " + conNum +  " inches in " + num + " centimeters.";
            }
   }

http://jsfiddle.net/7fw5ubvo/1/

需要注意的事项:

  • .match()方法返回一个数组,而不是字符串。你的代码可以工作,因为你的正则表达式不包括任何组,但我无论如何都会解决这个问题。

  • 呼叫:

    parseInt(num);
    

    对任何事情都没有影响。然而,仅此一点不会有什么影响,因为您将num*/运算符一起使用,这无论如何都会将字符串(再次来自数组)转换为数字。但是,它不会强制该值为整数。

  • 数字匹配器正则表达式坚持输入字符串的数字部分位于字符串的末尾。这就是$的含义。因此,只有像inches centimeters 5这样的字符串才能找到数字。