I have this:
var ID= "12,32,23,78";
var i = ID.split(',');
If I do this then it works fine, but when it is only one value like 12, then it gives me 0. How I can solve this issue? If I need to check for开发者_如何转开发 only one value, how do you do that?
If the variable "ID" is the number 12, then of course it doesn't work — the .split()
method is a method for strings, not numbers. Try this:
var ID = /* whatever */;
var i = (ID + '').split(',');
var i;
if (ID.indexOf(",") != -1)
i = ID.split(',');
else
i = ID;
Exactly like what you posted except you check for the presence of the seperator with JavaScripts .indexOf() string method.
var ID= "12,32,23,78";
var i = ID.split(',');
will return [12,32,23,78]
var ID= "12";
var i = ID.split(',');
will return [12] -- this is also an array
however you may do this
var ID= "12";
var i = ID.split(',') || ID;
String.prototype.mySplit = function(sep) {
return (this.indexOf(sep) != -1) ? this.split(sep) : [this];
};
Example:
//var ID= '12,32,23,78';
var ID= '12';
//Update
if (typeof(ID)=='number') ID += '';
var i = ID.mySplit(',');
alert(i[0]);
精彩评论