如何将其变成自我调用函数?

时间:2016-12-04 04:26:01

标签: javascript

我不确定如何将此功能变成自我调用功能。我的代码循环遍历JS文件中的一系列邮政编码,并将其从最小到最大排序并输出。我在网上发现在newZipCodeArray函数的末尾添加“())”应该自行调用该函数。但是,它不起作用。我做错了什么?

[enter image description here][1]

// Global variable
var zipCodeArray = [];

(function newZipCodeArray(currentZipCode) {

    var valueFound = false;
    for (zipCodeIndex = 0; zipCodeIndex <= zipCodeArray.length; zipCodeIndex++) {
        if (currentZipCode === zipCodeArray[zipCodeIndex]) {
            valueFound = true;
        }
    }
    if (valueFound === false) {
        zipCodeArray.push(currentZipCode);
    }
}());

function newZipCodeArrayssignment12_3() {
    // Instantiate variables.
    var output;
    var zipCodeRecords;

    // Get the element.
    output = document.getElementById('outputDiv');

    zipCodeRecords = openZipCodeStudyRecordSet();

    // Call the function to read the next record.
    while (zipCodeRecords.readNextRecord()) {
        currentZipCode = zipCodeRecords.getSampleZipCode();
        newZipCodeArray(currentZipCode);
    }

    // Sort the zip code array.
    zipCodeArray.sort();
}

1 个答案:

答案 0 :(得分:1)

立即调用(或自调用)函数中涉及的语法不允许从其他地方调用它。只需要调用一次函数时,就可以使用IIFE模式。

  

注意:

     

function包裹newZipCodeArraynewZipCodeArray(); // first call function newZipCodeArray(currentZipCode) { // ... } function newZipCodeArrayssignment12_3() { // ... while (zipCodeRecords.readNextRecord()) { // ... newZipCodeArray(currentZipCode); // additional calls } // ... } grouping parenthesis更改为declaration。并且,作为表达式,其名称不会被添加到周围范围以供其他代码引用。

要立即调用For example: "zab" There are 6 substrings "z", "a", "b", "za", "ab", "zab" of string "zab" in str. 并稍后再次允许它,您需要从中删除括号并在单独的语句中按名称调用它:

         for (int i=0;i<length;i++) {
             String suffix = p.substring(i,length);
             if(isPresent(suffix)) {
                 sum += (suffix.length()*(suffix.length()+1))/2;
                 break;
             } else {
                 sum++;
             }
         }