通过 String.prototype 函数设置 String,不返回
我有以下函数将 splice 添加到字符串:
String.prototype.splice = function(index, howManyToDelete, stringToInsert) {
var characterArray = this.split('');
Array.prototype.splice.apply(characterArray, arguments);
return characterArray.join('');
}
但是它的工作方式与我需要的 Array.prototype.splice 完全一样。数组拼接返回被删除的值。所以我只需要知道如何为 String
设置新值,而不必返回该值。
String.prototype.splice = function(index, howManyToDelete, stringToInsert) {
var characterArray = this.split(''),
retVal = Array.prototype.splice.apply(characterArray, arguments);
newstringvalue = characterArray.join('');
return retVal;
}
编辑:
显然你不能这样做,这就足够了:
String.prototype.splice = function(index, howManyToDelete, stringToInsert) {
var characterArray = this.split(''),
rem = Array.prototype.splice.apply(characterArray, arguments);
return {'s' : characterArray.join(''), 'x' : rem.join('')};
}
I have the following function to add splice
to a string:
String.prototype.splice = function(index, howManyToDelete, stringToInsert) {
var characterArray = this.split('');
Array.prototype.splice.apply(characterArray, arguments);
return characterArray.join('');
}
However it does quite work exactly like Array.prototype.splice
, which I need it to. The array splice returns the values which were removed. So I just need to know how to set a new value to a String
without having to return the value.
String.prototype.splice = function(index, howManyToDelete, stringToInsert) {
var characterArray = this.split(''),
retVal = Array.prototype.splice.apply(characterArray, arguments);
newstringvalue = characterArray.join('');
return retVal;
}
Edit:
Apparently you can't do that, this will have to suffice:
String.prototype.splice = function(index, howManyToDelete, stringToInsert) {
var characterArray = this.split(''),
rem = Array.prototype.splice.apply(characterArray, arguments);
return {'s' : characterArray.join(''), 'x' : rem.join('')};
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能那样做。您无法像更改数组内容那样更改字符串的值。
查看其他字符串方法,以及它们如何返回新字符串值而不是就地更改字符串。
You can't do that. You can't change the value of a string in the way that you change the content of an array.
Look at the other string methods, and how they return the new string value rather than changing the string in place.