0

我正在尝试比较 2 个字符串是否相等,并返回不同位置的任何不同字母的数量,如果有任何例如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");
4

3 回答 3

0

除了西蒙的回答之外,您还没有返回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;
};
于 2013-08-31T13:20:57.307 回答
0
numDiffChar += index;

Won't increase numDiffChar with 1 each time but with the value of index. I'm guessing you want to do

numDiffChar++;
于 2013-08-31T13:12:58.583 回答
0

函数等于(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++;
    }
}
}

};

相等(“javascript”,“JavaScript”);

于 2013-08-31T13:49:44.297 回答