索引如何返回此示例的位置,结果不应该是 -1
How is indexOf returning the position of this example, shouldn't the result be -1?
我知道indexOf
搜索字符串/数组中值的位置,然后返回位置,但我认为即使有空格,它也必须是完全匹配的。 但是我正在阅读这篇文章,我很困惑为什么即使比赛只是部分比赛,它也会返回真实。
通常这就是 indexOf 返回的方式,并且符合预期
var array = ["AA", "BB", "A", "CC", "D", "This is the time to be back home.", "It's christmas"];
// Let's say result >= 0 will return true else false
console.log(array.indexOf("AA") + " AA"); // 0 --true
console.log(array.indexOf("A") + " A"); // 2 --true
console.log(array.indexOf("C") + " C"); // -1 --false
console.log(array.indexOf("DD") + " DD"); // -1 --false
console.log(array.indexOf("the time") + " the time"); // -1 --false
console.log(array.indexOf("It's christmas") + " christmas"); // 6 --true
这是我在一本书中看到的,不明白为什么它会返回在数组中找到的真实含义。
String.prototype.cliche = function(){
var cliche = ["lock and load", "touch base", "open the kimono"];
for (var i = 0; i < cliche.length; i++){
var index = this.indexOf(cliche[i]);
if(index >= 0){
return true;
}
}
return false;
}
var sentences = ["I'll send my car around to pick you up.",
"Let's touch base in the morning and see where we are",
"We don't want to open the kimono, we just want to inform them."];
for(var i = 0; i < sentences.length; i++){
var phrase = sentences[i];
if(phrase.cliche()){
console.log("CLICHE ALERT: " + phrase);
}
}
函数中的陈词滥调数组只有部分短语,如touch base
等
但是在句子数组中,该值就像Let's touch base in the morning and see where we are
indexOf
实际上为此返回 true,即使它只是部分短语与陈词滥调的值匹配。
这是如何工作的?
那是因为它们是不同的方法:
-
Array.prototype.indexOf
返回在数组中找到某个值(使用严格相等算法)的第一个位置。 -
String.prototype.indexOf
返回字符串中包含某个字符串(是子字符串)的第一个位置。
例:
["AA"].indexOf("A"); // -1 (not found)
"AA".indexOf("A"); // 0
相关文章:
- 谷歌位置服务附近搜索结果基于正确的地图中心的位置
- 在谷歌地图上显示所有搜索到的位置结果
- 需要呈现MongoDB查询返回结果的特定索引/位置
- 为什么由于数组中数字1的位置,我会从函数中得到不同的结果
- 1行代码(console.log),代码中的两个位置=两个结果差异
- 为多个表单动态指定输出ajax成功结果的位置
- 隐藏的“纬度”和“lng”字段没有被删除,所以我的脚本仍在从不正确的地理位置中搜索纬度和液化天然气结果
- 查找主干集合上的位置仅返回一个结果
- 记录选定的文本位置,给出错误的结果
- 索引如何返回此示例的位置,结果不应该是 -1
- 返回到 ajax 结果页面上上次看到的位置
- 绝对位置;在不同的屏幕上获得不同的结果
- 两个按钮,可随背景位置变化而切换,并在输入中显示结果
- 如何从谷歌位置/地图获得更多结果
- 获取插入符号位置的常见解决方案会返回奇怪的结果
- 如何在mongodb / mongoose查询中改变基于参数的结果位置
- Javascript获取元素的值和位置,并将结果保存在对象数组中
- 如何将JavaScriptObject结果添加到SmartGWT中生成的HTML的特定位置
- 谷歌地图位置API地址自动完成和显示选择的结果
- Javascript和CSS动画没有将我的结果放在正确的位置