Console.log上的随机数

时间:2016-11-01 11:00:21

标签: function console console.log

如何创建一个单独的函数,如果我的randNum = 7,它将是console.log"你好"。仅使用javascript。

感谢。

function randomNumber() {
        var randNum = Math.floor(Math.random() * (25)) + 1;
        console.log(randNum);

      } 

3 个答案:

答案 0 :(得分:1)

function randomNumber() {

    var randNum = Math.floor(Math.random() * (25)) + 1;

    return randNum;

}

function logRandomNumber() {

    var randNum = randomNumber();

    if(randNum == 7) { 

        console.log('hello');

    }

}

logRandomNumber();

答案 1 :(得分:1)

function randomNumber() 
{
        var randNum = Math.floor(Math.random() * (25)) + 1;
        (randNum==7)?console.log("hello"):console.log(randNum); 

}

//如果您需要其他功能

function randomNumber1() 
{
        var randNum = Math.floor(Math.random() * (25)) + 1;
        if(randNum===7)
          SeparateFunc();


}

function SeparateFunc(){
console.log("hello");

}
  

JSFiddle:https://jsfiddle.net/y918ndu0/

答案 2 :(得分:0)

  function randomNumber() {
    var randNum = Math.floor(Math.random() * (25)) + 1;
    if(randNum == 7){
      hello();
    }

  }

 function hello(){
   console.log('hello');
 }

将控制台日志包装在if语句中,该语句检查生成的随机数的值。

新函数将具有控制台日志,并在if语句正确时调用

function randomNumber() {
    var randNum = Math.floor(Math.random() * (25)) + 1;
      hello(randNum);
  }

 function hello(randNum){
   if(randNum == 7)
    console.log('hello');
   }
}

所以你将randNum变量传递给它将检查的函数