我需要对数据集进行排序,如您所见,我已将其分配给记录变量。根据该数据,我需要查看邮政编码是否存在。如果邮政编码不存在,那么我需要将其移入数组(当然会有重复)并继续检查其余的记录,如果确实存在,我就不需要做任何事情。
// Declare Array
var numbersArray = [];
// Variables
var records;
var zipCode;
var numbers;
var index;
var output;
var outputMessageOne;
var outputMessageTwo;
var count = 0;
output = document.getElementById('outputDiv');
records = openZipCodeStudyRecordSet();
output.innerHTML = "The unique zip codes are: ";
while (records.readNextRecord()) {
zipCode = records.getSampleZipCode();
for (index = 0; index < numbersArray.length; index++) {
if (zipCode === numbersArray[index]) {
var uniqueZip = false;
break;
records++;
}
if (zipCode !== numbersArray[index]) {
numbersArray.push(zipCode);
}
}
output.innerHTML += numbersArray;
}
}
答案 0 :(得分:4)
您可以像这样简化for循环:
matchedZip = false;
for(i in numbersArray) {
if (numbersArray[i] === zipCode) {
matchedZip = true;
}
}
if ( ! matchedZip) {
numbersArray.push(zipCode);
}
尝试将其插入到while循环中。如果在for循环中有数组推送,那么每次没有匹配时,你最终会推送每个邮政编码。
答案 1 :(得分:0)
嗯,你没有提出问题,但我会回答:)答案是你不应该使用普通数组,而是使用地图或关联数组。幸运的是,可以使用普通的Javascript对象:
var numbers = {};
// Variables
var records;
var numbers;
var index;
var output;
var outputMessageOne;
var outputMessageTwo;
var count = 0;
output = document.getElementById('outputDiv');
records = openZipCodeStudyRecordSet();
output.innerHTML = "The unique zip codes are: ";
while (records.readNextRecord()) {
var zipCode = records.getSampleZipCode();
numbers[zipCode] = 1; // just picking an arbitrary value
}
for (var zipCode: numbers) {
output.innerHTML += zip + " ";
}
原因是这样您就不需要遍历每个新输入的现有数据。