比较2个字符串并返回不属于't相等

compare 2 strings and return the number of letters that aren't equal

本文关键字:相等 不属于 返回 2个 字符 字符串 串并 比较      更新时间:2023-09-26

我试图比较两个字符串是否相等,并在不同的地方返回任何不同字母的数量,如果有,例如bobbuy将返回2。

我在其他地方没有找到任何其他这样的例子,所以我试着自己写代码。我下面的代码没有返回任何内容-不确定它出了什么问题?任何想法都值得赞赏。

感谢

    function equal(str1, str2) {
    /*If the lengths are not equal, there is no point comparing each character.*/
    if (str1.length != str2.length) {
        return false;
    }
    /*loop here to go through each position and check if both strings are equal.*/
    var numDiffChar = 0;
    var index = 0;
    while (index < str1.length) {
        if (str1.charAt(index) !== str2.charAt(index)) {
            numDiffChar += index;
            index++;
        } else {
            index++;
        }
    }
 };
 equal("javascript", "JavaScript");
numDiffChar += index;

不会每次将numDiffChar增加1,而是使用index的值。我猜你想做

numDiffChar++;

除了Simon的答案之外,您不会返回numDiffChar的值。此外,无论如何,您总是希望递增index,所以我将把它放在if语句之外。如果条件相同,你可以提前保释。建议:

function equal(str1, str2) {
    /* If the strings are equal, bail */
    if (str1 === str2) {
        return 0;
    }
    /*If the lengths are not equal, there is no point comparing each character.*/
    if (str1.length != str2.length) {
        return false;
    }
    /*loop here to go through each position and check if both strings are equal.*/
    var numDiffChar = 0;
    var index = 0;
    while (index < str1.length) {
        if (str1.charAt(index) !== str2.charAt(index)) {
            numDiffChar++;
        }
        index++;
    }
    return numDiffChar;
};

函数等于(str1,str2){

/*If the lengths are not equal, there is no point comparing each character.*/
if (str1.length != str2.length) {
    return false;
}
/*loop here to go through each position and check if both strings are equal.*/
else
{
var numDiffChar = 0;
var index = 0;
while (index < str1.length) {
    if (str1.charAt(index) !== str2.charAt(index)) {
        numDiffChar += index;
        index++;
    } else {
        index++;
    }
}
}

};

equal("javascript"、"javascript");