参数和局部变量有什么不同? [英] What is the different between a parameter and a local variable?

查看:115
本文介绍了参数和局部变量有什么不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉看似非常愚蠢的问题。

我目前正在使用codecadamy,这让我失望:

I'm currently working through codecadamy, and this is throwing me off:

 var greeting = function(name) {
    name = "sausage";
    console.log(name); 
};

greeting(name);

我知道我会得到 sausage

为什么我不写 var name =sausage; ?有什么区别?

Why don't I just write var name = "sausage";? What is the difference?

推荐答案

c> function(name)是一个参数。也就是说,它用于将数据传递到函数中。但是,参数是局部变量。在函数内部为 name 赋值有点奇怪。我想你会想做这样的事情:

The name in function(name) is a parameter. That is, it is used to pass data into the function. But, parameters are local variables. Assigning a value to name inside the function is a little strange though. I would assume you want to do something like this:

 var greeting = function(name) {         
     console.log(name); 
  };

  greeting("sausage");

在此版本的代码中,您通过参数<将值sausage传递给函数code>名称。这很有用,因为您可以多次调用该函数,并且每次函数可以根据您传递的内容打印不同的值。

In this version of the code you are passing the value "sausage" into the function via the parameter name. This is useful because you can call the function many times and each time the function may print a different value depending on what you pass.

这篇关于参数和局部变量有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆