简体   繁体   English

如何比较字符串字母(javascript)

[英]How to compare string letters (javascript)

Hey I've been trying to write a simple javascript function for comparing string letters but i can't make it work for some reason...here is the code. 嘿,我一直在尝试编写一个简单的JavaScript函数来比较字符串字母,但是由于某种原因我无法使其正常工作……这里是代码。

function compare(wordOne, wordTwo) {
    if (wordOne.substring(0) === wordTwo.substring(0))
    {
        return true;
    } else {
        return false;
    }
}
compare("house", "hell");

Assuming you want to compare the first letter of the two strings, you can use the following code 假设您要比较两个字符串的第一个字母,可以使用以下代码

function compare(wordOne, wordTwo) {
    return wordOne[0] === wordTwo[0];
}
compare("house", "hell");

This condenses the if / else condition, as you are just interested in whether the first letters are equal - not in how different they are. 这使if / else条件更加简洁,因为您只对第一个字母是否相等感兴趣,而不是对它们的区别感兴趣。 You can also use str.toUpperCase() (or) str.toLowerCase() in order to make the comparison case insensitive. 您也可以使用str.toUpperCase() (或) str.toLowerCase()使比较大小写不敏感。

As per @Josh Katofsky's suggestion, you can of course make this function more versatile by - for instance - adding a third parameter that tests the n-th letter: 按照@Josh Katofsky的建议,您当然可以通过以下方式使此功能更加通用:-例如,添加测试第n个字母的第三个参数:

function compare(wordOne, wordTwo, index) {
    return wordOne[index] === wordTwo[index];
}
compare("house", "hell", 0);

To explain why your current code doesn't work, you need to pass a second parameter to .substring as the to value. 为了解释为什么当前代码无法正常工作,您需要将第二个参数传递给.substring作为to值。 String.substring(0) just returns the whole string after the 0th character, so the entire word. String.substring(0)仅返回第0个字符之后的整个字符串,因此返回整个单词。 Fixed example; 固定示例;

function compare(wordOne, wordTwo) {
    if (wordOne.substring(0, 1) === wordTwo.substring(0, 1)) {
        return true;
    }
    else 
    {
        return false;
    }
}

compare("house", "hell");

You could also just use wordOne[0] === wordTwo[0] 您也可以只使用wordOne[0] === wordTwo[0]

substring returns the part of the string between the start and end indexes, or to the end of the string . substring返回字符串在开始索引和结束索引之间或字符串结尾的部分

If you want to compare only first character, use charAt 如果只想比较第一个字符,请使用charAt

function compare(wordOne, wordTwo) {
   return wordOne.charAt(0) === wordTwo.charAt(0);
}
compare("house", "hell");

Or you can pass the index as the parameter 或者您可以将索引作为参数传递

function compare(wordOne, wordTwo, index) {
   return wordOne.charAt(index) === wordTwo.charAt(index);
}
compare("house", "hell", 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM