我有两个数组,我需要相互检查,如果它们已经达到每个数组中的两个项目实际上彼此相同的程度,则在某处附加一些 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,并从 courseHwork 数组中的匹配对象附加该属性“title”。
注意:我实际的 daysArray 包含数字作为字符串“1”-“31”,对象的 courseHwork 数组是动态填充的,因此它可以包含任意数量的对象,但是没有对象的属性值会超过“31” "在找到的子字符串中。
*问题: 我如何遍历两个数组,并且每次在两个数组之间找到匹配值时,都会找到一个 html 元素,该元素也包含完全相同的值,然后附加一些内容?*
最佳答案
这是我想出的想法:
var daysArray = ["1", "2", "3", "4", "5", "12"];
var courseHwork = ["4", "8", "15", "16", "23", "42", "12"];
for (var i = 0; i < courseHwork.length; i++) {
for (var j = 0; j < daysArray.length; j++) {
if (courseHwork[i] == daysArray[j]) {
$('div:contains("'+daysArray[j]+'")').append("<div class='assignment'>"+courseHwork[i]+" - appended</div>");
}
}
}
你可以在这里找到它:http://jsfiddle.net/4cqCE/2/
好吧,检查一下这是否是您想要的。首先它在 2 个数组中寻找相同的值,如果找到它,它会将一些内容附加到包含“4”的 div。这是你想要的吗?
这是一个包含 2 个相同值的示例,其中包含 2 个 div,每个包含一个值。 http://jsfiddle.net/4cqCE/3/
关于javascript - 比较两个数组以寻找匹配值的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9639065/