Javascript检查函数的结果是否已经输出,如果是,则运行该函数

时间:2015-11-15 16:23:22

标签: javascript function

我提前为我糟糕的英语道歉。

我制作了一个javascript函数gen(),它通过添加从两个数组中随机选择的两个值来生成一个值。

我想创建一个运行gen()的函数,只有在之前从未输出过的值才输出该值,否则会再次执行函数gen()

提前致谢。

gen()函数的代码:



function gen() {
		var s = ["a", "b"];
		var c = ["c", "d"];

		var MbSubj = ["Hello", "Hi", "Hey"];
		var MaSubj = ["John", "Jack", "Matt"];
		var FbSubj = ["Lara", "Juliet"];
		var FaSubj = ["Lora", "Elise"];

		var sRand = s[Math.floor(Math.random() * s.length)];
		var cRand = c[Math.floor(Math.random() * c.length)];
		var FbSubjRand = FbSubj[Math.floor(Math.random() * FbSubj.length)];
		var MbSubjRand = MbSubj[Math.floor(Math.random() * MbSubj.length)];
		var FaSubjRand = FaSubj[Math.floor(Math.random() * FaSubj.length)];
		var MaSubjRand = MaSubj[Math.floor(Math.random() * MaSubj.length)];

		function mb() {
				return MbSubjRand + MaSubjRand;
		}

		function ma() {
			return MaSubjRand + MbSubjRand;
		}

		function fb() {
				return FbSubjRand + MaSubjRand;
		}

		function fa() {
				return FaSubjRand + MbSubjRand;
		}

		if (sRand === "a" && cRand === "b") {
				mb();
		} else if (sRand === "b" && cRand === "c") {
				ma();
		} else if (sRand === "a" && cRand === "d") {
				fb();
		} else {
				fa();
		}
}




1 个答案:

答案 0 :(得分:1)

保持变量,如果您已经运行 gen ,如果是,则不再运行,如果没有,请运行它:

JSFiddle:http://jsfiddle.net/0j8wqswn/

function gen(){
    alert('this is the gen function')
}


(function(){
    var alreay_run=false;
    new_function=function(){
        if(alreay_run) return
        alreay_run=true
        gen();
    }
})()


//Let's Test
new_function()
new_function()
new_function()

//You will see alert only one time