Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果字符等于字符列表_Javascript_Charat - Fatal编程技术网

Javascript 如果字符等于字符列表

Javascript 如果字符等于字符列表,javascript,charat,Javascript,Charat,我想要Javascript中的如下内容 如果str.charAt(index)(在以下集合中){“,”,“#”,“$”,“;”,“:”} 是的,我知道这一定很简单,但我似乎无法正确理解语法。我现在拥有的是 theChar = str.charAt(i); if ((theChar === '.') || (theChar === ',') || (theChar === ... )) { // do stuff } 这是可行的,但一定有更好的办法 编辑:我这样做了,但不确定它是否好: va

我想要Javascript中的如下内容

如果str.charAt(index)(在以下集合中){“,”,“#”,“$”,“;”,“:”}

是的,我知道这一定很简单,但我似乎无法正确理解语法。我现在拥有的是

theChar = str.charAt(i);
if ((theChar === '.') || (theChar === ',') || (theChar === ... )) {
  // do stuff
}
这是可行的,但一定有更好的办法

编辑:我这样做了,但不确定它是否好:

var punc = {
    ".":true,
    ",":true,
    ";":true,
    ":":true
};

if (punc[str.charAt[index]) { ...

可以使用正则表达式执行此操作:

var theChar = str.charAt(i);
if (/[.,#$;:]/.test(theChar)) {
  // ...
}

用这些字符定义一个数组,然后在数组中搜索。一种方法是:

var charsToSearch = [".", ",", "#", "$", ";", ":"];
var theChar = str.charAt(i); /* Wherever str and i comes from */

if (charsToSearch.indexOf(theChar) != -1) {
    /* Code here, the char has been found. */
}

对新的JavaScript程序员不太友好,但我想展示一个实用的解决方案是很好的。@MattiasBuelens我想这取决于新的JavaScript程序员来自哪里:)当我学习JavaScript时,我已经知道正则表达式很长时间了。啊,这就是我想做的,但是我被集合分散了注意力。@L105你确定吗?要做一个jsPerf。当你做的时候,也要用
String.indexOf
做一个,例如
“,#$:”。indexOf(theChar)!==-1
。尽管我认为性能对这个代码片段来说并不重要。字符串
indexOf
在Firefox中最快,其次是正则表达式,然后是数组。在Chrome中正好相反。在我的测试中,正则表达式在Chrome中慢59%,第二次:慢9%。