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

时间:2018-10-02 16:10:53

标签: javascript html

我正在尝试将时间转换为分钟。只要输入“ X小时”,它就会在几分钟内转换为X小时。我正在使用的函数抛出错误,提示include不是函数。我在同一项目中使用过包含,因此我不确定为什么会收到此错误。

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 个答案:

答案 0 :(得分:1)

我在Firefox和Chrome中测试了您的代码...一切都很好。 IE11当然会引发错误。参见compatibility for includes。如果要考虑与IE的兼容性,则应使用indexOf()而不是include。

因此,您将使用if (prep.includes('hours'))来代替if (prep.indexOf('hours') > -1)

答案 1 :(得分:0)

您的代码段应该可以在Internet Explorer以外的现代浏览器上正常运行。查看下面的图片以了解受支持的浏览器。

Browser Support

您可以使用indexOf方法。