简体   繁体   English

函数返回值返回未定义

[英]Function return value returns as undefined

function getRent(rent){
    var rent = 666;
    return rent;
}
function show(){

getRent();
alert(rent);
}

Why is this not working? 为什么这不起作用? It comes out as rent undefined? rent不确定吗?

There are multiple things wrong with this code. 此代码有很多错误。

For one you are redefining the rent variable by using the var keyword in your getRent function. 对于其中一个,您正在使用getRent函数中的var关键字重新定义rent变量。

Secondly when you call getRent you are not assigning its return value to anything and you are effectively asking the console to display an undefined variable. 其次,当您调用getRent时,您并未将其返回值分配给任何对象,而实际上是在要求控制台显示未定义的变量。

What you want is 你想要的是

function getRent(){
    var rent = 666;
    return rent;
}

var rent = getRent();
alert(rent);

or perhaps 也许

function getRent(rent){
    rent = 666;
    return rent;
}

var param = 1; //sample variable to change
var rent = getRent(param);
alert(rent);

You aren't assigning the return value of getRent() to anything. 您没有将getRent()的返回值分配给任何东西。 rent is only defined in the getRent function. rent仅在getRent函数中定义。

var rent = getRent();
alert(rent);

You define rent in getRent() and not in show() . 您在getRent()定义rent ,而不是在show()定义rent So rent is not defined in your case. 因此,您的情况未定义rent

Try : 尝试:

function getRent(rent){
    var rent = 666;
    return rent;
}
function show(){
  alert(getRent("params"));
}

You need to store the returned value of getRent(). 您需要存储getRent()的返回值。

function getRent(){
    var rent = 666;
    return rent;
}
function show(){
    var theRent = getRent();
    alert(theRent);
}

The reason it doesn't work as you expected is because rent , defined inside getRent , is not accessible outside of the function. 如你预期它不工作的原因是因为rent ,里面定义getRent ,是不是功能的外部访问。 Variables declared inside functions using the var keyword are only "visible" to other code inside that same function, unless you return the value to be stored in a variable elsewhere. 在函数内部使用var关键字声明的变量仅对同一函数内的其他代码“可见”,除非您返回要存储在其他变量中的值。

It may help you to read up on the basics of functions and function parameters in JavaScript. 它可以帮助您阅读JavaScript中的函数和函数参数的基础知识。 Here is a good article: http://web-design-weekly.com/blog/2013/01/20/introduction-to-functions-in-javascript/ 这是一篇好文章: http : //web-design-weekly.com/blog/2013/01/20/introduction-to-functions-in-javascript/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM