简体   繁体   English

如何创建类似于string.split()的自定义函数来反转字符串

[英]How to create a custom function similar to string.split() to reverse a string

I'm trying to write a function on which if we pass the string like we do for split, it returns a string which is reversed - 我正在尝试编写一个函数,如果我们像传递split那样传递字符串,它将返回一个相反的字符串-

This is what I've tried - 这就是我尝试过的-

var abc = "hello"
var result;
String.prototype.reverser = function(str){
  var temparr = str.split('').reverse().join('');
  return temparr;
}
result = abc.reverser();
console.log(result);

I'm expecting olleh but rather getting - 我期待olleh,但宁愿得到-

VM1179:4 Uncaught TypeError: Cannot read property 'split' of undefined at String.reverser (:4:19) at :7:14 VM1179:4未被捕获的TypeError:无法读取在7:14在String.reverser(:4:19)处未定义的属性'split'

You don't need a parameter str . 您不需要参数str The string is already binded to the method on prototype. 该字符串已绑定到原型上的方法。 Just use this to access the string. 只需使用this来访问字符串。

 var abc = "hello" var result; String.prototype.reverser = function(){ return this.split('').reverse().join(''); } result = abc.reverser(); console.log(result); 

Note: You shouldn't directly add enumerable properties to prototype . 注意:您不应该直接将可枚举的属性添加到prototype Instead use Object.defineProperty() 而是使用Object.defineProperty()

 var abc = "hello"; Object.defineProperty(String.prototype,'reverser',{ value:function(){ return this.split('').reverse().join(''); } }) var result = abc.reverser(); console.log(result) 

When extending String.prototype with your reverser() function, the string with the new method on it can be accessed with this ; 当使用您的reverser()函数扩展String.prototype ,可以使用this访问带有new方法的字符串。 the way you have defined it expects an argument (str) , that isn't provided. 您定义的方式需要一个未提供的参数(str) See how this can be used to access the string in this working snip: 怎么看this可以用来访问该工作剪断的字符串:

 var abc = "hello" var anotherStr = "what do you know?" var result; var anotherResult; String.prototype.reverser = function(){ var temparr = this.split('').reverse().join(''); return temparr; }; result = abc.reverser(); anotherResult = anotherStr.reverser(); console.log(result); console.log(anotherResult); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM