我希望能够在javascript中说出这样的话:
"a".distance("b")
如何将自己的距离函数添加到字符串类?
您可以扩展String原型;
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");