var Nanprocessor = function (entry) {
if(entry=="NaN") {
return 0;
} else {
return entry;
}
}
outputfield.value = Nanprocessor(x);
// where x is a value that is collected from a from field
// i.e say x =parseInt(formfield1.value);
//////////////////////////////////////////////////////
function ToInt(x){x=parseInt(x);return isNaN(x)?0:x;}
//////////////////////////////////////////////////////
var x = ToInt(''); //-> x=0
x = ToInt('abc') //-> x=0
x = ToInt('0.1') //-> x=0
x = ToInt('5.9') //-> x=5
x = ToInt(5.9) //-> x=5
x = ToInt(5) //-> x=5
// This is a safety check to make sure the prototype is not already defined.
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
return this;
}
};
// returns the int value or -1 by default if it fails
Number.method('tryParseInt', function (defaultValue) {
return parseInt(this) == this ? parseInt(this) : (defaultValue === undefined ? -1 : defaultValue);
});
// returns the int value or -1 by default if it fails
String.method('tryParseInt', function (defaultValue) {
return parseInt(this) == this ? parseInt(this) : (defaultValue === undefined ? -1 : defaultValue);
});
如果你不想使用安全检查,使用
String.prototype.tryParseInt = function(){
/*Method body here*/
};
Number.prototype.tryParseInt = function(){
/*Method body here*/
};
使用示例:
var test = 1;
console.log(test.tryParseInt()); // returns 1
var test2 = '1';
console.log(test2.tryParseInt()); // returns 1
var test3 = '1a';
console.log(test3.tryParseInt()); // returns -1 as that is the default
var test4 = '1a';
console.log(test4.tryParseInt(0));// returns 0, the specified default value