//我试图通过提示输入4个单词并将它们拆分并将每个单词分配给变量
var answer = prompt("Enter a sentence");
for(var i = 0; i < answer.length; i++){
if(answer[i] === " "){
var firstWord = answer.slice(0, answer.indexOf(" "));
var secondWord = answer.slice(answer.indexOf(" ") + 1, name.indexOf(" "));
var thirdWord = answer.slice();
var fourthWord = answer.slice();
}
}
答案 0 :(得分:0)
您可以利用字符串的.split()
方法。
溶液:
var answer = prompt("Enter a sentence");
var words = answer.split(" ");
var firstWord = words[0];
var secondWord = words[1];
var thirdWord = words[2];
var fourthWord = words[3];
这取决于您的提示是否以单个空格分隔,而您只输入4个单词。 .split()
是一个方法,它将查看调用它的字符串,并将字符串拆分为一个数组,由参数值(在本例中为“”)分隔。