检查是否定义了所有值,而不是空字符串

时间:2018-03-10 09:50:55

标签: javascript nan arrow-functions

我试图简化以下验证,因此我可以使用简单的短箭头功能:

var isARealNumber = (val) => val !== "" && val !== undefined;

"" >= 0会将""投放到0,所以它不起作用,但我正在寻找类似的东西。



var values1 = ["", "1", "2"];
var values2 = [undefined, "1", "2"];
var values3 = ["0", "1", "2"];

var isARealNumber= (val) => val !== "" && val !== undefined;

console.log(values1.every(isARealNumber));
console.log(values2.every(isARealNumber));
console.log(values3.every(isARealNumber));




1 个答案:

答案 0 :(得分:1)

您可以在RegExp方法中使用RegExp#test

var values1 = ["", "1", "2"];
var values2 = [undefined, "1", "2"];
var values3 = ["0", "1", "2"];
var reg = /^\d+$/

var isARealNumber= (val) => reg.test(val);

console.log(values1.every(isARealNumber));
console.log(values2.every(isARealNumber));
console.log(values3.every(isARealNumber));