JavaScript函数和参数

时间:2013-08-13 07:13:20

标签: javascript undefined

这是一个非常简单的JavaScript代码但我得到了 undefined 错误,我不知道我做错了什么。我从以下脚本得到的结果是很高兴见到你,undefinedRaj 。有人可以解释一下未定义的内容,以及如何删除它。

   var greeting = function (name) {
   document.write("Great to see you," + " " + name);
   };

   document.write(greeting(name) + "Raj");

6 个答案:

答案 0 :(得分:5)

您有两个名为name的变量。一个是您创建的函数的本地,另一个是全局的。

永远不会定义全局的。因此,当您致电greeting(name)时,您将name作为undefined传递。这意味着局部变量也是undefined

你的意图可能是:

  1. "Raj"作为name
  2. 的值传递
  3. 要不document.write函数的返回值(由于您没有return语句,它也是undefined
  4. 这样:

    var greeting = function (name) {
        document.write("Great to see you," + " " + name);
    };
    
    greeting("Raj");
    

答案 1 :(得分:2)

我相信你想这样做:

var greeting = function (name) {
    return "Great to see you," + " " + name;
};
document.write(greeting("Raj"));

答案 2 :(得分:1)

您必须将"Raj"作为参数传递给greeting方法。

应该是

var greeting = function (name) {
   document.write("Great to see you," + " " + name);
};

greeting("Raj");

var greeting = function (name) {
   return "Great to see you," + " " + name;
};
document.write(greeting("Raj"));

在你的代码中发生的事情是greeting()首先调用全局变量名称,它引用window.name默认为'',因此它打印Great to see you,,然后返回调用undefined,然后document.write(greeting(name) + "Raj")执行greeting(name),如前所述返回undefined,因此打印undefinedRaj,结果

答案 3 :(得分:1)

该函数无法正常工作,因为它什么都不返回,有两种方法可以做到:

var greeting = function (name) {
   document.write("Great to see you," + " " + name);
   };

greeting("Raj");

或者

 var greeting = function (name) {
      return ("Great to see you," + " " + name);
       };

document.write(greeting("Raj"));

答案 4 :(得分:0)

如果你想要

  

很高兴见到你,Raj

结果, 你应该打电话

greeting("Raj");
在您编写的代码中

,您正在调用document.write(greeting(name)) 但你之前没有定义名字, 所以你得到这个“undefinedRaj”消息

答案 5 :(得分:0)

由于您已在函数中使用document.write(),因此在调用函数时不需要它 干杯http://jsfiddle.net/bQcWX/

var greeting = function (name) {
   document.write("Great to see you," + " " + name);
};

greeting("Raj");