【问题标题】:Why doesn't this piece of code replace the first letter of each word? [duplicate]为什么这段代码不替换每个单词的第一个字母? [复制]
【发布时间】:2019-04-08 16:59:04
【问题描述】:

我试图替换每个单词的第一个字母并想出了这段代码。有谁知道为什么它不起作用?

name = 'EFEIN DOED'
name.split(' ').map(b => {
   b = b.toLowerCase();
   console.log(b);
   b[0] = 3;
   console.log(b);
   return b;
}).join(' ');

提前谢谢你。

【问题讨论】:

  • b[0] = 3 - 字符串是不可变的,不能写入索引。
  • @AlexK。你是对的,谢谢。就是这样。
  • name.replace(/(^|\s)\w/g, "$1"+3)也可以用来代替split, map and than join

标签: javascript arrays node.js reference pass-by-reference


【解决方案1】:

您的总体想法是正确的,只是字符串是不可变的,因此不能以这种方式进行编辑。这是一个返回 '3fein 3oed' 的替代方法:

name.split(' ').map(b => '3' + b.toLowerCase().substring(1)).join(' ');

【讨论】:

  • name.replace(/(^|\s)\w/g, "$1"+3)也可以用来代替split, map and than join
  • 您还需要将其分配给一个新变量以使用它,因为“名称”变量是不可变的(如上所述)。 const newName = name.split(' ').map(b => '3' + b.toLowerCase().substring(1)).join(' ');
猜你喜欢
  • 1970-01-01
  • 2019-11-17
  • 1970-01-01
  • 1970-01-01
  • 2022-08-24
  • 1970-01-01
  • 1970-01-01
  • 2014-04-11
  • 1970-01-01
相关资源
最近更新 更多