我想在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");
this
返回的是一个对象,例如 String {0: "t", 1: "e", 2: "s", 3: "t", length: 4, [[PrimitiveValue]]: "test"}
。要使用实际的文本内容,我需要调用 this.toString()
。 - Wesley SmithArray.prototype.myFunc = function(a)
和 [/*...*/].myFunc(5)
不能正常工作。 - undefinedString.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 );
==================================================
String.prototype.toJadeCase()
。而这个答案帮助了我实现它。 - Sunny PrakashObject.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()
添加属性。但是可以通过使用 Window.prototype
而不是 String.prototype
,将属性添加到所有对象中。 - undefinedString.prototype.distance = function (){
//your code
}
var dom; //you can replce this to be $ just like jQuery
dom = function(elm) {
if(typeof elm === "object") {
// already done example
//typeof document.getElementById('id') will be object
return [elm];
} else {
return document.querySelectorAll(elm);
}
} // Returns elements by all css selector eg
// .class #id id p id > p id ~ p in short any css selectors
Object.prototype.text = function(txt) { //object prototype as NodeList returned would be object or maybe displayed as [Object NodeList]
var i = 0; //loop through the elements
for(i; i < this.length; i++) {
this[i].innerHTML = txt;
}
// in this function this refers to object that this function is passed on
};
dom('.classh').text('Changed for elements with classh');
dom('#heading').text('Changed for elements with id heading'); //examples