Javascript、字符串、正则表达式、if和else if、console.log不同的输出

Javascript、字符串、正则表达式、if和else if、console.log不同的输出,javascript,regex,if-statement,Javascript,Regex,If Statement,我想按顺序输出字符串的元音,所以我决定使用正则表达式来实现 但是,当我将表达式放在(if和else if)中的不同位置时,同一表达式的输出是不同的。有人能解释一下吗 function ordered_vowel_word(str) { if(str.match(/[aeiou]{1,}/g) !== ""){ var arr = str.match(/[aeiou]{1,}/g); console.log(arr); } else console.log

我想按顺序输出字符串的元音,所以我决定使用正则表达式来实现

但是,当我将表达式放在(if和else if)中的不同位置时,同一表达式的输出是不同的。有人能解释一下吗

function ordered_vowel_word(str) {

  if(str.match(/[aeiou]{1,}/g) !== ""){
  var arr = str.match(/[aeiou]{1,}/g);
      console.log(arr);
  }
  else
      console.log(str);
  }

ordered_vowel_word("bcg");
ordered_vowel_word("eebbscao");
/*输出*/

有序元音单词(“bcg”)

==>空

有序元音词(“eebbscao”)

==>[“ee”,“ao”]

但如果我重新构造表达式

function ordered_vowel_word(str) {

  if(str.match(/[^aeiou]/) !== "")
      console.log(str); 
  else if(str.match(/[aeiou]{1,}/g) !== ""){
  var arr = str.match(/[aeiou]{1,}/g);
      console.log(arr); 
  }
}
输出将是

有序元音单词(“bcg”)

==>bgv

有序元音词(“eebbscao”)


==>eebbscao

str.match的返回值您使用它的方式是一个数组,它在匹配时包含匹配项。而且,当没有匹配项时,它不是空字符串。。。它实际上是空的

尝试将if条件下的测试内容更改为:

str.match(/[aeiou]{1,}/g) !== null)

请注意,
string.match
如果至少有一个匹配项,则返回一个数组,如果没有匹配项,则返回null

我想你想要的是:

if(str.match(/[aeiou]{1,}/g)==null){//没有匹配项

if(str.match(/[aeiou]{1,}/g)!=null){//有匹配项

至于排序,您必须处理使用
str.match
获得的数组


检查排序数组。是的,您可以使用
什么让您感到惊讶?您的两个输入都满足第一个
if
条件下一个问题:在OP的情况下,它不是
null
,我将其更改为null,并按照OP的预期运行。该[]=[]非常奇怪,感谢您指出了输出的一些代码,这样对于OP来说很明显您的意思是正确的,但是'bcg'。match(/[aeiou]{1,}/g)实际上是空的。