我正在尝试为Java脚本解决代码。但是我注意到我的while循环无法正常工作。基本上,我正在尝试制作猪拉丁文翻译器。谁能建议我如何运行代码? 这是我的代码:
s = "this is a sentence"
words = s.split(' ')
document.write(words.length)
//document.write(" ")
//document.write(words[1])
var empty = ["this","is","sentence"]
counter = 0
while(counter == words.length){
first_letter = words[counter].substring(0,words[counter].length)+"ay";
//new = words[first_letter]+"ay"
empty.push(first_letter);
counter = counter + 1;
}
document.write(empty)
答案 0 :(得分:1)
我认为您在while循环中输入了错误的条件。在第一个实例本身中,它返回false,因为counter=0
和words.length = 4
。它仅在counter=4
时执行代码。我认为您需要在其中放置while(counter < words.length)
,这意味着执行代码直到单词的最后一个字母。告诉我是否可行。
将第一个字母放在最后一个字母然后添加“ ay”是一个示例,可能会有所帮助。
var word = "Word";
var first_letter = word.substring(0,1);
var word_without_first_letter = word.slice(1,word.length);
var new_word = word_without_first_letter + first_letter+"ay";
alert(new_word);
答案 1 :(得分:1)
s = "this is a sentence"
words = s.split(' ')
document.write(words.length)
//document.write(" ")
//document.write(words[1])
var empty = ["this","is","sentence"]
counter = 0
while(counter !== words.length){
first_letter = words[counter].substring(1,words[counter].length)+words[counter].slice(0,1)+"ay";
//new = words[first_letter]+"ay"
empty.push(first_letter);
counter = counter + 1;
}
document.write(empty)
while循环中使用的条件不正确。Counter必须“不等于” word.length,然后它才会进入while循环内部。