javascript - js字符串的操作问题
巴扎黑
巴扎黑 2017-04-10 17:52:29
[JavaScript讨论组]

将 var str = 'this-is-str';将'-'后的字母大写,即修改为thisIsStr的最简单方法是什么呢.

补充一下自己写的代码,感觉写的比较繁琐.

a = a.replace(a[0] , a[0].toUpperCase());
for(var i in a ){
    if(a[i] === '-'){
        a = a.replace(a[i] + a[parseInt(i) + 1] , a[parseInt(i) + 1].toUpperCase());
    }
}

而且有一个疑问,为什么

typeof(i) == String;

根据楼下的代码,自己写成了reduce的形式,感觉其实没什么区别:

var a = "this-is-st".split('-');
a = a.reduce(function(pre,next){
    pre += next.charAt(0).toUpperCase() + next.substr(1);
    return pre;
},'');
巴扎黑
巴扎黑

全部回复(3)
迷茫

不用正则的话,可以这么做。核心思想还是先分组然后reduce。

function camelCase(string, separator) {
  const capitalize = str => {
    const lower = str.toLowerCase();
    return lower.charAt(0).toUpperCase() + lower.slice(1);
  };

  return string.split(separator).reduce((result, item, index) => {
    const lowerCase = item.toLowerCase();
    return result + (index ? capitalize(lowerCase) : lowerCase);
  }, '');
}
typeof(i) == String;

关于这个问题,其实没什么好说的,Arrayindex本身就是一个String,跟你遍历的是不是String对象没有关系。之所以arr[1]能用,是系统自动帮你转换成String了。

Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 232−1.

http://www.ecma-international.org/ecma-262/5.1/#sec-15.4

PHP中文网
var str = 'this-is-str';
var r = /(-)(\w)/g;
str = str.replace(/(-)(\w)/g,function(match,p1,p2){
    return p2.toUpperCase();
});
怪我咯

感觉自己的也不是很简洁,不过可以通过正则表达式来实现。

    var a = "this-is-st".split('-');
    for(var i=1;i<a.length;i++){
      a[i] = a[i].charAt(0).toUpperCase()+a[i].substr(1);
    }
   typeof(i) == String; 
   

是由于你遍历的是一个字符串这里说法错误,经过在chrome console中验证的确与类型无关。

    var arr = {a:1,b:[1]}
    for(var i in arr){
      console.log(typeof i);     //输出两次string
    }
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号