处理完函数后删除字符串返回

时间:2011-07-16 20:29:01

标签: javascript join return

我是初学者和学生,我希望有人可以帮助我。我有一个任务,我需要将程序分解为3个函数。第一个从用户那里取一个句子,第二个根据每个单词的长度将句子转换成新的“猪语言”,第三个在控制台中显示结果。我完成了这个程序的核心,但是我在清除返回字符串时遇到了问题。具体来说,一旦用户完成了所有3个步骤,我不希望他们能够进入程序的第3部分并再次看到结果。我希望他们必须回到起点。很抱歉这么做,但我只是不确定如何解释它 这是我的代码:

function prog1(){
var userLang = prompt("Type in your sentence");
//If the user enters an empty string
    if(userLang == ""){
        console.log("You must enter a sentence");
    }
//If the user presses cancel
    else if(userLang == null){
        wantToQuit = true;
    }
//If the user enters in a good string
    else {
        console.log("Thank you, now go to program 2");
        been2prog1 = true;
        return userLang;
    }
} 

function prog2(){
//sets newLang = userLang and splits the string
var newLang = prog1Lang.split(" ");

//enters loop to find length of each split word
var x = 0;
for( x = 0; x < newLang.length; x++ ){

//if it's 5 or less words, add -oink    
    if ((newLang[x].length) <= 5){
        newLang[x] += "-oink";
    }
//if it's more than 5 words, add -a
    else {
        newLang[x] += "-a";

    }       

}
**newLang.join(" ");**  

//put the string back together  

console.log("String converted");
been2prog2 = true;
return newLang;
}

 function prog3(){
var endLang = prog2Lang;
console.log(endLang);
**delete prog2Lang;**

}

我认为“删除”可能会起作用,如上所示,但我并没有做任何事情。然后我在想一个布尔,但我不知道该怎么做。任何帮助将不胜感激。

最后一件事,我也坚持如何将我的字符串连接在一起。目前,它将它作为数组的一部分记录在控制台中,并用引号和逗号分隔每个单词。我查了一下.join();而且我认为它会起作用,但它似乎也没有用。我把它放在函数2中的if else语句中,但是当我这样做时它只是吓坏了,所以对这个问题的指点也会非常感激。

谢谢!

2 个答案:

答案 0 :(得分:0)

尝试将newLang.join分配给自己..

newLang = newLang.join(" ");

答案 1 :(得分:0)

我不确定你遇到麻烦的另一点是什么,我有点困惑。

如果您要做的只是清除字符串变量,那么..

prog2Lang = null;

or 

prog2Lang = ""; 

null是一个空对象,“”是一个空字符串。

那是你的追求吗?