2017-02-23 70 views
0

我有一个猪拉丁翻译器的功能,除了当一个单词以辅音簇开始时(> 1辅音)为什么我的JavaScript猪拉丁翻译器插入额外的逗号?

这里是我的功能:

function translatePigLatin(str) { 
    var firstVowel = str.indexOf(str.match(/[aeiou]/)); 
    if (firstVowel===0){ 
    return str + "way"; 
    } 
    else { 
    var charArray = str.split(""); 
    return charArray.slice(firstVowel, str.length).join("") + charArray.slice(0, firstVowel) + "ay"; 
    } 
} 

translatePigLatin("california")应该返回 “aliforniacay”,并执行。

translatePigLatin("glove")应该返回“oveglay”,但它返回“oveg,lay”。

任何想法都来自逗号?

+1

缺少来自第二个'.slice'的'.join(“”)' – JJJ

+0

提示:发生这种情况是因为您正在对数组进行字符串化。 – robertklep

+0

@robertklep这是错误的方法?什么会更好? –

回答

1

我相信你需要将字符串拆分成数组。将下面的满足您的需求?:

function translatePigLatin(str) { 
 
    var firstVowel = str.indexOf(str.match(/[aeiou]/)); 
 
    return str.slice(firstVowel) + str.slice(0, firstVowel) + "ay"; 
 
} 
 
console.log(translatePigLatin("california")) 
 
console.log(translatePigLatin("glove"))

+0

是的,这是一个更好的方式 –

1

有趣的是,逗号从array + "string"操作到来。

console.log([1,2] + "string") // Returns '1,2string'

在你的情况 - 你是不是参加第二(charArray.slice(0, firstVowel))阵列。