小编典典

将方法添加到字符串类

javascript

我希望能够在javascript中说出这样的话:

   "a".distance("b")

如何将自己的距离函数添加到字符串类?


阅读 365

收藏
2020-05-01

共1个答案

小编典典

您可以扩展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");
2020-05-01