我有两个数组需要相互比对,如果两个数组中的每个元素都相同,则在某个位置附加一些HTML代码。
这是我尝试的示例代码:
var daysArray = ["1", "2", "3", "4", "5"];
var courseHwork = ["4", "8", "15", "16", "23", "42"];
所以在上述数组中只有一个匹配的值,为“4”。
以下是下一部分:
for (var i = 0; i < courseHwork.length; i++) {
//in my actual code courseHwork contains several objects, each of which
//has a duedate property, so here I want to see if this part of the duedate
//property is equal to any position in the daysArray array.
if (courseHwork[i].duedate.substring(8,10) === daysArray[i]) {
//here I mean to select an element of this class that contains a string
//that is equal to that of the matching positions in both arrays. then
//once found it should take the title property from one of the objects in the
//courseHwork array and append it there.
$('.fc-day-number:contains("'+daysArray[i]+'")').append("<div class='assignment'>"+courseHwork[i].title+"</div><br />");
}
}
如果按计划运行,它会找到一个包含字符串 "4" 的 div,并将与 coursesHwork 数组中匹配对象的 'title' 属性附加到该 div 上。
注意:我的 daysArray 实际上涵盖了数字作为字符串 "1"-"31",并且对象数组 courseHwork 是动态生成的,因此可以包含任意数量的对象,但没有一个对象的属性值超过正在查找的子字符串 "31"。
问题:如何循环遍历两个数组,并每次在两个数组之间找到匹配值时,找到一个还包含完全相同值的 html 元素,然后将某些内容附加到该元素上?
courseHwork[i].duedate
表示courseHwork
是一个对象数组,为什么一开始你把它声明成了一个字符串数组呢? - Aprillion