代码之家  ›  专栏  ›  技术社区  ›  Raviga

Includes在函数参数上使用时不是函数

  •  1
  • Raviga  · 技术社区  · 6 年前

    function calcTotalCook(prep, rest, cook) {
      //console.log(rest);
    
      if (prep.includes('hours')) {
        prep = prep.replace('hours', '');
        prep = Number(prep) * 60;
      }
    
      if (rest.includes('hours')) {
        rest = rest.replace('hours', '');
        rest = Number(rest) * 60;
      }
    
      if (cook.includes('hours')) {
        cook = cook.replace('hours', '');
        cook = Number(cook) * 60;
        console.log(cook);
      }
    
      document.getElementById('totalTime').innerText = Number(prep) + Number(rest) + Number(cook);
    }
    <div class="fourth clearfix">
      <h2>Prep Time:</h2>
      <input type="text" id="prepTime" name="prepTime" class="inputField" value="">
    </div>
    <div class="fourth">
      <h2>Rest Time:</h2>
      <input type="text" id="restTime" name="restTime" class="inputField" value="">
    </div>
    <div class="fourth">
      <h2>Cook Time:</h2>
      <input type="text" id="cookTime" name="cookTime" class="inputField" value="">
    </div>
    <div class="fourth">
      <h2>Total Time:</h2>
      <label id="totalTime" name="totalTime"></label>
    </div>
    <input type="button" class="addButton" value="Calc" onclick="calcTotalCook(document.getElementById('prepTime').value, document.getElementById('restTime').value, document.getElementById('cookTime').value);">
    2 回复  |  直到 6 年前
        1
  •  1
  •   Darren    6 年前

    我在Firefox和Chrome上测试了你的代码。。。一切都很好。IE11当然是在抛出错误。看到了吗 compatibility for includes . 如果与IE的兼容性是一个问题,你应该使用 indexOf()

    所以 if (prep.includes('hours')) if (prep.indexOf('hours') > -1) .

        2
  •  0
  •   Dan    6 年前

    你的代码片段应该可以很好地与现代浏览器除了Internet Explorer。检查下面的图像以了解支持的浏览器。

    Browser Support

    相反,你可以使用 indexOf