Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'd like to be able to say something like this in javascript :(我想能够在javascript中说出这样的话:)

"a".distance("b") How can I add my own distance function to the string class?(如何将自己的距离函数添加到字符串类?)   ask by will translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
345 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can extend the String prototype;(您可以扩展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"); See a JSFiddle here .(在这里查看JSFiddle 。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...