【问题标题】:Current code needs to be IIFE(Self-Invoked) - Code works and runs当前代码需要是 IIFE(自调用) - 代码工作并运行
【发布时间】:2019-10-03 01:27:28
【问题描述】:

我目前对如何使我的代码 IIFE 进行自我调用感到困惑。问题陈述是:

您的客户希望从邮政编码研究中获得邮政编码列表(每个仅列出一次),按从小到大的顺序排列。他希望它“运行”(自调用)。

我的代码显示正确的输出,其中所有邮政编码从最小到最大,并且只列出一次。我需要帮助了解如何使我当前的代码成为“自我调用”。这是我当前的代码:

//Start.
window.onload = uniqueZipcodes;
function assignment12_3() {
    // Your code goes in here.
}

function uniqueZipcodes(){

    //Start.
    //Variables
    var records, zip;
    var output = document.getElementById("selfInvokingFunctionDiv");
    var zipcodes = [];
    var outputString = "";

    //Gets the records...
    records = openZipCodeStudyRecordSet();
    //This will loop through the records and put unique records
    //into an array
    while(records.readNextRecord()){
        zip = records.getSampleZipCode();
        if(!zipcodes.includes(zip)){
            zipcodes.push(zip);
        }
    }

    //Will sort the zipcodes
    zipcodes.sort();

    //outputs the zipcodes.
    for(var z in zipcodes){
        outputString += zipcodes[z] + "</br>";
    }

    outputDiv.innerHTML += outputString;
};

【问题讨论】:

  • (function() { your code will immediately invoke here })()
  • 这个作业让我很困惑。我不知道IIFE 除了function() {...}() 是什么意思,但要说'[客户] 希望它“运行”'......什么?我的意思是,代码不只是运行,您在定义它之后直接调用它。我是否遗漏了什么,或者这个作业是否表明未能掌握IIFE 的概念?

标签: javascript node.js iife self-invoking-function


【解决方案1】:

你可以在它第一次加载时调用它:

function assignment12_3() {
    // Your code goes in here.
}

assignment12_3();  // invoke it once

或者:

(function assignment12_3() {
    // Your code goes in here.
})()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 2016-09-20
    • 2018-09-27
    • 1970-01-01
    • 2017-09-17
    • 2019-03-05
    • 2016-01-21
    相关资源
    最近更新 更多