4

我为我的新手道歉,但我不清楚如何在函数外部访问函数内的变量。我知道您需要向他们介绍一些方法,但我不能 100% 确定原因和方法。

以下面的代码为例,我想var degree在函数之外使用整个代码。我该怎么做?

function DegreeToMil() 
{

//Degree's to Mils: 1 Degree = 17.777778 Mils

var degree = 10;
var mils = degree * 17.777778;

return mils;

 }
4

2 回答 2

4

它实际上相当简单,只需在函数之外定义它。

编辑:更新了一个例子,并解释了做了什么以及它是如何工作的。

    DegreesToMils.degrees = 10; /* This is a static variable declaration to make sure it isn't undefined
                             * See note 1 below */

function DegreesToMils(degrees) {
    if (degrees !== undefined) {
        DegreesToMils.degrees = degrees; /* If the parameter is defined, 
                                          * it will update the static variable */
    }

    var milsPerDegree = 17.777778; /* This is a variable created and accessible within the function */

    return DegreesToMils.degrees * milsPerDegree; /* The function will return 177.77778 */
}

console.log(DegreesToMils.degrees); /* Prints 10, Note 1: This would be undefined if
                                     * not declared before the first call to DegreesToMils() with a 
                                     * defined parameter
                                     */
console.log(DegreesToMils(10)); /* Prints 177.77778 */
console.log(DegreesToMils(9)); /* Prints 160.00000200000002, Sets DegreesToMils.degrees to 9 */
console.log(DegreesToMils.degrees); /* Prints 9 */
于 2013-08-05T00:41:34.790 回答
1
function DegreeToMil() 
{

    //Degree's to Mils: 1 Degree = 17.777778 Mils

    var degree = 10;
    var mils = degree * 17.777778;
    var result = [degree, mils]; // it's an array
    return result;
}

// use it like this

var myResult = DegreeToMil();
console.log(myResult[0]); // degree
console.log(myResult[1]); // mils
于 2013-08-05T00:44:19.073 回答