我希望能够在 javascript 中说这样的话:
"a".distance("b")
如何将我自己的距离函数添加到字符串类?
我希望能够在 javascript 中说这样的话:
"a".distance("b")
如何将我自己的距离函数添加到字符串类?
您可以扩展String
原型;
String.prototype.distance = function (char) {
var index = this.indexOf(char);
if (index === -1) {
alert(char + " does not appear in " + this);
} else {
alert(char + " is " + (this.length - index) + " characters from the end of the string!");
}
};
...并像这样使用它;
"Hello".distance("H");
String.prototype.distance = function( arg ) {
// code
};
最小的例子:
没有人提到valueOf。
==================================================
String.prototype.
OPERATES_ON_COPY_OF_STRING = function (
ARGUMENT
){
//:Get primitive copy of string:
var str = this.valueOf();
//:Append Characters To End:
str = str + ARGUMENT;
//:Return modified copy:
return( str );
};
var a = "[Whatever]";
var b = a.OPERATES_ON_COPY_OF_STRING("[Hi]");
console.log( a ); //: [Whatever]
console.log( b ); //: [Whatever][Hi]
==================================================
从我对它的研究来看,没有办法就地编辑字符串。
即使您使用字符串对象而不是字符串原语。
下面不起作用并且在调试器中得到非常奇怪的结果。
==================================================
String.prototype.
EDIT_IN_PLACE_DOES_NOT_WORK = function (
ARGUMENT
){
//:Get string object:
var str = this;
//:Append Characters To End:
var LN = str.length;
for( var i = 0; i < ARGUMENT.length; i++){
str[LN+i] = ARGUMENT[ i ];
};
};
var c = new String( "[Hello]" );
console.log( c );
c.EDIT_IN_PLACE_DOES_NOT_WORK("[World]");
console.log( c );
==================================================
经过多年(和 ES6)......我们有了一个新的选择来做到这一点:
Object.defineProperty( String.prototype, 'distance', {
value: function ( param )
{
// your code …
return 'counting distance between ' + this + ' and ' + param;
}
} );
// ... and use it like this:
const result = "a".distance( "b" );
console.log(result);
你可以这样做:
String.prototype.distance = function (){
//your code
}