本文介绍了反字符串情况(javascript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,它接受字符串并将所有小写字母更改为大写,反之亦然。 较低的UPPER将转换为LOWER upper

I'm trying to write a function that takes the string and changes all the lowercase letters to uppercase and vice versa. "lower UPPER" would translate to "LOWER upper"

继承我所拥有的:

var convertString = function (str){
var s = '';
var i = 0;
while (i < str.length) {
    var n = str.charAt(i);
        if (n == n.toUpperCase()) {
            n = n.toLowerCase;
        }
        else {
            n = n.toUpperCase;
        }

 i +=1; 
 s += n;

}
return s;
};
convertString("lower UPPER");

我正在使用工作,并得到一个非常奇怪的消息输出。

I'm using this website to work and am getting a pretty weird message outputted.

推荐答案

除了 if 语句之外,你几乎所有内容都是正确的。您将 n 设置为等于其 toLowerCase toUpperCase 方法,而不是其返回值。您需要调用这些方法并将 n 设置为等于其返回值:

You have just about everything correct, except for inside of your if statement. You're setting n equal to its toLowerCase or toUpperCase method, not its return value. You need to call those methods and set n equal to their return values:

var convertString = function (str) {
    var s = '';
    var i = 0;
    while (i < str.length) {
        var n = str.charAt(i);
        if (n == n.toUpperCase()) {
            // *Call* toLowerCase
            n = n.toLowerCase();
        } else {
            // *Call* toUpperCase
            n = n.toUpperCase();
        }

        i += 1;
        s += n; 
    }
    return s;
};

convertString("lower UPPER");






您获得的输出('function toUpperCase(){[native code]} ... )是每个方法转换为字符串的结果,然后连接到结果字符串。您可以通过在控制台中运行以下任一命令来获得相同的结果:


The output that you're getting ('function toUpperCase() { [native code] }...) is the result of each method being converted to a string, then concatenated to your result string. You can achieve the same result by running either of these commands in your console:


  • console.log( .toUpperCase);

  • console.log(。toUpperCase.toString());

  • console.log("".toUpperCase);
  • console.log("".toUpperCase.toString());

两者的结果都是函数toUpperCase(){[native code]}

快乐编码!

这篇关于反字符串情况(javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 05:12