JS小白的问题

function titleCase(str) {
        str = str.toLowerCase().split(' ')

        .map(function(word){//区别在这里
            return(word.charAt(0).toUpperCase() + word.slice(1));
        })
        return str.join(' ');
    }    
        console.log(titleCase("I'm a little tea pot")); 
function titleCase(str) {
        str = str.toLowerCase().split(' ');

        str.map(function(word){ //区别在这里
            return(word.charAt(0).toUpperCase() + word.slice(1));
        })
        return str.join(' ');
    }    
        console.log(titleCase("I'm a little tea pot")); 

为什么第一个代码能走map函数?而第二个没有,只不过是赋值了给str在调用而已,为什么没有生效?

阅读 4.1k
6 个回答
function titleCase(str) {
        str = str.toLowerCase().split(' ');

       str =  str.map(function(word){ //区别在这里
            return(word.charAt(0).toUpperCase() + word.slice(1));
        })
        return str.join(' ');
    }    
        console.log(titleCase("I'm a little tea pot")); 

其实是你自己的写法比较有欺骗性,如果第一个你写成

function titleCase(str) {
         str = str.toLowerCase().split(' ').map(function(word){})
        return str.join(' ');
    }    
        console.log(titleCase("I'm a little tea pot")); 

第二个则是

function titleCase(str) {
         str = str.toLowerCase().split(' ')
         str.map(function(word){})
        return str.join(' ');
    }    
        console.log(titleCase("I'm a little tea pot")); 

使用map会返回一个新数组,原数组不变,第二个str处理后,返回新数组你没有赋给任何值,而原数组str又没变,显示出 “map没有生效”的效果

Definition and Usage

The map() method creates a new array with the results of calling a function for every array element.

The map() method calls the provided function once for each element in an array, in order.

Note: map() does not execute the function for array elements without values.

Note: map() does not change the original array.

参见:JavaScript Array map() Method

数组的map方法返回的是一个新的数组,你只需将str用map方法转换过后的新数组用一个变量保存起来,然后在String.split()去转化就可以了。哦,原来上面的已经回答了。

先学js,再学nodejs。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题