我有几件事情我想用foreach取代(这是一类我正在要求),但是他们没有一个人工作:的forEach与在
我最初对于代码(此作品正确显示内容):
for (var i in education.schools) {
$('#education').append(HTMLschoolStart);
var formattedName = HTMLschoolName.replace('%data%', education.schools[i].name).replace('#', education.schools[i].url);
var formattedLocation = HTMLschoolLocation.replace('%data%', education.schools[i].location);
var formattedDegree = HTMLschoolDegree.replace('%data%', education.schools[i].degree);
var formattedMajors = HTMLschoolMajor.replace('%data%', education.schools[i].majors);
var formattedDates = HTMLschoolDates.replace('%data%', education.schools[i].dates);
var formattedNameDegree = formattedName + formattedDegree;
$('.education-entry:last').append(formattedNameDegree);
$('.education-entry:last').append(formattedDates);
$('.education-entry:last').append(formattedLocation);
$('.education-entry:last').append(formattedMajors);
}
我的forEach变化(不显示任何内容,所有内容将消失):
education.schools.forEach(function() {
$('#education').append(HTMLschoolStart);
var formattedName = HTMLschoolName.replace('%data%', education.schools[i].name).replace('#', education.schools[i].url);
var formattedLocation = HTMLschoolLocation.replace('%data%', education.schools[i].location);
var formattedDegree = HTMLschoolDegree.replace('%data%', education.schools[i].degree);
var formattedMajors = HTMLschoolMajor.replace('%data%', education.schools[i].majors);
var formattedDates = HTMLschoolDates.replace('%data%', education.schools[i].dates);
var formattedNameDegree = formattedName + formattedDegree;
$('.education-entry:last').append(formattedNameDegree);
$('.education-entry:last').append(formattedDates);
$('.education-entry:last').append(formattedLocation);
$('.education-entry:last').append(formattedMajors);
})
第二个是一个if语句,我应该更换的一部分与forEach。
if语句工作正常,像这样唯一的问题是它只有整整7个项目好,如果我再添加到阵列我也将必须更新此:
if (bio.skills.length > 0) {
$('#header').append(HTMLskillsStart);
var formattedSkill = HTMLskills.replace('%data%', bio.skills[0]);
$('#skills').append(formattedSkill);
var formattedSkill = HTMLskills.replace('%data%', bio.skills[1]);
$('#skills').append(formattedSkill);
var formattedSkill = HTMLskills.replace('%data%', bio.skills[2]);
$('#skills').append(formattedSkill);
var formattedSkill = HTMLskills.replace('%data%', bio.skills[3]);
$('#skills').append(formattedSkill);
var formattedSkill = HTMLskills.replace('%data%', bio.skills[4]);
$('#skills').append(formattedSkill);
var formattedSkill = HTMLskills.replace('%data%', bio.skills[5]);
$('#skills').append(formattedSkill);
var formattedSkill = HTMLskills.replace('%data%', bio.skills[6]);
$('#skills').append(formattedSkill);
}
foreach循环码(代替阵列中显示每个项目的它显示阵列中的所有项目七次,基本上它似乎来遍历它的正确的次数,但所有7项输出到每次迭代):
if (bio.skills.length > 0) {
$('#header').append(HTMLskillsStart);
bio.skills.forEach(function(){
var formattedSkill = HTMLskills.replace('%data%', bio.skills);
$('#skills').append(formattedSkill);
})
}
因为'我'不存在于forEach – Li357
[不要使用'for ... in'列举数组!](https://stackoverflow.com/q/500504/1048572) – Bergi