Writing my own split method
I found out earlier today that split() doesn't work if attached to a single value. I would like to write my own split() method so that if I sent it a single v开发者_C百科alue, it creates an array with a single value.
Q: Should I change the split prototype or write a function?
var SPLIT=function(X) {
return X.toString().split()
}
To clarify, split()
does work with a "single value". The problem in your last question was that the value returned was not a string, and hence the .toString()
is necessary.
In my opinion, there's no need to write another function for this. Simply remember to convert your values to a string before calling .split()
on it.
If you must have a function that does this, then to answer your question, create a new function and don't modify the prototype. While it may seem harmless to modify the prototype of Number or Object in this case, it's generally considered bad practice as other code (e.g. libraries you're using) may not be expecting it.
精彩评论