首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript在数组中查找子类

JavaScript在数组中查找子类
EN

Stack Overflow用户
提问于 2013-11-18 05:00:24
回答 2查看 104关注 0票数 0

我试图验证输入字段,以查看输入的值是否包含字符串开头的数字或字母X或Y:

代码语言:javascript
复制
var t_index_array = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'X', 'Y'];

for(var i=0, l=t_index_array.length; i < l; i++){
   if (document.form.topography_index.value.toUpperCase().substr(0,1) != t_index_array[i]){
    alert ( "The Topography index field needs to start with a number between 0 and 9 or the letters X or Y." );
    valid = false;
    return valid;
   }
}

由于t_index_arrayi的值总是为0,所以这是不起作用的。有什么想法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-11-18 05:04:37

当前的逻辑是检查它是否以每个字符开始,而不是其中的一个字符(这当然是不可能的)。

相反,你的意思是:

代码语言:javascript
复制
var t_index_array = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'X', 'Y'];

if(!t_index_array.some(function(val) {
    return document.form.topography_index.value.toUpperCase().substr(0,1) == val
})) {
    alert("The Topography index field needs to start with a number between 0 and 9 or the letters X or Y.");
    return false;
}
return true;

但我会用正则表达式,这就更简单了。

代码语言:javascript
复制
if(!/^[0-9xy]/i.test(document.form.topography_index.value)) {
    alert("The Topography index field needs to start with a number between 0 and 9 or the letters X or Y.");
    return false;
}
return true;

编辑:/^[0-9xy]/i的解释。

  • ^匹配在输入开始。
  • [0-9xy]字符0到9,或x,或y
  • i案例-无意义
票数 3
EN

Stack Overflow用户

发布于 2013-11-18 05:05:18

你可以用regex来处理这个案子。

代码语言:javascript
复制
var patt1 = /^[\dXY]/i;
var result =inputfield.match(patt1);
//the result will hold the expected output

如果结果是null..then,则它不以数字或x或y开头

谢谢你@RobG

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20040392

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档