通过String.prototype函数设置String而不返回 [英] Set String via String.prototype function without return

查看:164
本文介绍了通过String.prototype函数设置String而不返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能将 splice 添加到字符串中:

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('');
}

然而它确实完全像 Array.prototype .splice ,我需要它。数组拼接返回已删除的值。所以我只需要知道如何将新值设置为 String ,而不必返回值。

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;
}

编辑:
显然你不能这样做,这将必须足够:


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('')};
}


推荐答案

你做不到。您不能以更改数组内容的方式更改字符串的值。

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.

这篇关于通过String.prototype函数设置String而不返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆