我需要检查一个数组是否包含字符串值或数值。我在javascript中检查以下代码。但是下面的代码不起作用。
$(function() {
var data = ["0", "1", "2"];
var isAlpha = false;
var alphabetRegex = /^[a-zA-Z]*$/; ///^[a-zA-Z ]*$/
arrayLen = data.length;
//checking if array is alphabet
while (--arrayLen) {
if (alphabetRegex.test(data[arrayLen])) {
isAlpha = true;
break;
}
}
if (isAlpha == true) { //this condition for alphabet sorting
//......code here
} else { //this condition only for number values
//code here
}
});
答案 0 :(得分:0)
下面的代码对我有用。 我已将if条件更改为
if (data[arrayLen].trim().match(/\D/)) {
而不是
if (alphabetRegex.test(data[arrayLen]))
完整代码:
$(function() {
var data = ["0", "1", "2"];
var isAlpha = false;
arrayLen = data.length;
//checking if array is alphabet
while (--arrayLen) {
if (data[arrayLen].trim().match(/\D/)) {
isAlpha = true;
break; //break the loop if even single array value contains string
}
}
if (isAlpha == true) { //this condition for alphabet sorting
//......code here
} else { //this condition only for number values
//code here
}
});