gpt4 book ai didi

javascript - 使用 indexOf() 比较数组中的字符

转载 作者:数据小太阳 更新时间:2023-10-29 03:49:10 26 4
gpt4 key购买 nike

  function mutation(arr) {

var tester = arr[1].split('');

for (var i = 0; i < tester.length; i ++) {
if (!arr[0].indexOf(tester[i])) return false;
}
return true;
}

mutation(["hello", "hey"]);

如果数组第一个元素中的字符串包含数组第二个元素中字符串的所有字母,我应该在此处返回 true。

我没有发现这段代码有任何问题,但它只通过了 90% 的测试,我不知道为什么。我在那里看不到模式——我应该满足什么确切条件才能通过测试。

最佳答案

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.

String.prototype.indexOf()如果找不到值,则返回 -1,这就是您的语句不起作用的原因。

更改为:

if (arr[0].indexOf(tester[i]) < 0) return false;

关于javascript - 使用 indexOf() 比较数组中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33776899/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com