javascript - 如何从 String.prototype 更改 String 的值?
问题描述
我写了这段代码:
String.prototype.toJadenCase = function () {
return this.split(/\s/).map(word => word[0].toUpperCase() + word.substr(1)).join(' ')
}
let text = 'hello world'
text.toJadenCase()
alert(text) // hello world
它不会改变字符串的值,从调用的函数是。正如我在这里看到的:String prototype changed the string value,它应该可以工作,但它没有
感谢所有的帮助!
解决方案
您不能更改字符串的值,字符串是不可变的。您所能做的就是创建一个新字符串并返回它:
text = text.toJadenCase()
// ^^^^^^^
String.prototype.toJadenCase = function () {
return this.split(/\s/).map(word => word[0].toUpperCase() + word.substr(1)).join(' ')
}
let text = 'hello world'
text = text.toJadenCase()
alert(text) // hello world
旁注:它不如String.prototype
其他一些重要,但最佳实践是将添加到内置原型中的任何内容(如果您向其中添加任何内容)定义为non-enumerable,这是您使用时的默认设置Object.defineProperty
:
Object.defineProperty(String.prototype, "toJadenCase", {
value: function () {
return this.split(/\s/).map(word => word[0].toUpperCase() + word.substr(1)).join(' ');
},
writable: true,
configurable: true
});
推荐阅读
- php - 我如何处理和限制在 laravel 项目上执行的查询数量?
- sqlite - 处理这个需要什么 SQLite 列数据类型?
- python - 有没有办法在多维数组的第一项中搜索项目?
- apache-kafka - 我可以让 Kafka 消费者/接收器连接以跳过主题中的特定分区吗?
- elasticsearch - 如何使用 NEST 对象初始化器语法自动映射 Elasticsearch 属性
- javascript - 根据条件值更改输入文本的背景颜色
- rest - 如何使用 curl 在 Dspace 6 REST API 中上传比特流
- mongodb - 在公有子网和私有子网 AWS 之间传递请求
- kubernetes - 使用 Spring 配置文件时,Apache Ignite .Net 节点不会启动
- hive - 按 id 将前 n 个频繁值转置到列