javascript:将方法添加到字符串类 [英] javascript: add method to string class

查看:111
本文介绍了javascript:将方法添加到字符串类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能在javascript中说出类似的内容:

I'd like to be able to say something like this in javascript :

   "a".distance("b")

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

How can I add my own distance function to the string class?

推荐答案

您可以扩展 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!");
    }
};

...并像这样使用它;

... and use it like this;

"Hello".distance("H");

在这里查看JSFiddle

这篇关于javascript:将方法添加到字符串类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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