我是 IIFE Functions 的新手,我很难理解如何实现它,但我确实理解它是什么以及它的目的是什么。问题陈述:
您的客户希望从邮政编码研究中获得邮政编码列表(每个仅列出一次),按从小到大的顺序排列。他希望它“只是运行”(自我调用)。
这是我的旧代码,它可以正常工作并正确显示邮政编码。我将显示我第一个运行的初始代码,但不被认为是自调用的:
window.onload = displayUniqueZipcodes;
function assignment12_3() {
// code goes in here.
}
// Logic to display the zipcodes.
function displayUniqueZipcodes(){
// Declare variables.
var records, zip;
var output = document.getElementById('outputDiv');
var zipcodes=[];
var outputString = "";
// Opens the records.
records = openZipCodeStudyRecordSet();
// Loops through records, pushes the unique records into the zipcodes array.
while(records.readNextRecord()){
zip = records.getSampleZipCode();
if (!zipcodes.includes(zip)){
zipcodes.push(zip);
}
}
// Sorts the zipcodes.
zipcodes.sort();
// outputs the zipcodes.
for (var v in zipcodes){
outputString += zipcodes[v] + "</br>";
}
output.innerHTML = outputString;
}
&这里是我现在不再显示邮政编码的代码以及我尝试利用 IIFE 功能的代码:
function assignment12_3() {
// Your code goes in here.
//Variables
var records, zip;
var output = document.getElementById("outputDiv");
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;
}();
谢谢你。