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在调用而已,为什么没有生效?
数组的map方法返回的是一个新的数组,你只需将str用map方法转换过后的新数组用一个变量保存起来,然后在String.split()去转化就可以了。哦,原来上面的已经回答了。
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
先学js,再学nodejs。
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"));
如何形象地解释 JavaScript 中 map、foreach、reduce 间的区别?
其实是你自己的写法比较有欺骗性,如果第一个你写成
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没有生效”的效果