【发布时间】:2023-03-25 23:13:01
【问题描述】:
我不确定我在这里做错了什么。我使用 indexOf 的第一个实例工作得很好,但是当我第二次使用它时,它没有返回我期望的结果。
function mutation(arr) {
//return arr;
res = "";
for (var x=0; x<arr[1].split("").length; x++) {
if (arr[0].indexOf(arr[1].split("")[x]) !== -1) {
res += "t";
} else {
res += "f";
}
}
// res = ttt
if (res.indexOf("f") !== -1) {
return true;
} else {
return false;
}
}
mutation(["hello", "hey"]);
// this returns true instead of false
mutation(["floor", "loo"]);
// returns false instead of true
如果 arr[1] 中的元素不存在于 arr[0] 中,则mutation 应返回 false,否则返回 true。
【问题讨论】:
-
你到底想做什么?
-
我刚刚将你的代码粘贴到 JS 控制台中,我也成功了
-
如果您使用的是 IE8 及以上版本,则不支持
.indexOf()。参考链接:stackoverflow.com/questions/3629183/… -
我正在使用 chrome 和 firefox。
-
@splucena 查看我编辑的答案。那里概述了您的代码的问题。你有一个 off by 1 错误和一个否定的 indexOf 检查。
标签: javascript