如果值存在,为什么 indexOf(char) 为 0?
Why is indexOf(char) is 0 if the value exists?
为什么是firstHalf.indexOf(secondHalfArr[i])
0
?
"use strict";
let word = "9999999999",
len = word.length,
oddSecondHalfStarter = (len % 2 == 0) ? len / 2 : 1 + len / 2,
firstHalf = word.substr(0, len / 2),
secondHalf = word.substr(oddSecondHalfStarter, len),
firstHalfArr = word.substr(0, len / 2).split(''),
secondHalfArr = word.substr(oddSecondHalfStarter, len).split(''),
firstHalfLength = firstHalf.length,
secondHalfLength = secondHalf.length,
charsToReplace = 0;
for (let i = 0; i < firstHalfLength; i++) {
if (firstHalf.indexOf(secondHalfArr[i]) < 1) {
charsToReplace++;
}
}
for (let i = 0; i < secondHalfLength; i++) {
if (secondHalf.indexOf(firstHalfArr[i]) < 1) {
charsToReplace++;
}
}
alert(charsToReplace);
indexOf()
方法 returns 指定值在字符串中第一次出现的位置。
此方法 returns -1 如果要搜索的值从未出现。 indexOf()
方法区分大小写。
确保在您的语句中使用 !== -1
以获得有效结果。
示例:
for (let i = 0; i < secondHalfLength; i++) {
if (secondHalf.indexOf(firstHalfArr[i]) !== -1) {
charsToReplace++;
}
}
为什么是firstHalf.indexOf(secondHalfArr[i])
0
?
"use strict";
let word = "9999999999",
len = word.length,
oddSecondHalfStarter = (len % 2 == 0) ? len / 2 : 1 + len / 2,
firstHalf = word.substr(0, len / 2),
secondHalf = word.substr(oddSecondHalfStarter, len),
firstHalfArr = word.substr(0, len / 2).split(''),
secondHalfArr = word.substr(oddSecondHalfStarter, len).split(''),
firstHalfLength = firstHalf.length,
secondHalfLength = secondHalf.length,
charsToReplace = 0;
for (let i = 0; i < firstHalfLength; i++) {
if (firstHalf.indexOf(secondHalfArr[i]) < 1) {
charsToReplace++;
}
}
for (let i = 0; i < secondHalfLength; i++) {
if (secondHalf.indexOf(firstHalfArr[i]) < 1) {
charsToReplace++;
}
}
alert(charsToReplace);
indexOf()
方法 returns 指定值在字符串中第一次出现的位置。
此方法 returns -1 如果要搜索的值从未出现。 indexOf()
方法区分大小写。
确保在您的语句中使用 !== -1
以获得有效结果。
示例:
for (let i = 0; i < secondHalfLength; i++) {
if (secondHalf.indexOf(firstHalfArr[i]) !== -1) {
charsToReplace++;
}
}