一个for循环比较两个数组寻找匹配值 [英] A for-loop that compares two arrays looking for matching values
问题描述
我有两个数组,我需要核对对方,如果他们已经达到了一个点,每个阵列中的两个项目实际上是彼此相同,然后附加一些HTML的地方。
I have two arrays that I need to check against each other and if they have reached a point where both items in each array are actually the same as one another, then append some html somewhere.
下面是code的某些位我一直在努力作为一个例子:
Here are some bits of the code I have been trying as an example:
var daysArray = ["1", "2", "3", "4", "5"];
var courseHwork = ["4", "8", "15", "16", "23", "42"];
所以在上面的阵列,只有一个匹配值,作为:4
so in the arrays above there is only one matching value, being: "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 />");
}
}
如果事情的来龙去脉按计划将找到一个div,包含字符串4,追加从courseHwork数组中的匹配对象属性称号。
If things worked as planned it will have found a div, that contains the string "4" and appended that property 'title' from the matching object in the courseHwork array.
请注意:我的实际daysArray涵盖数字为字符串1 - 31,和对象的courseHwork阵列的动态填充,因此它可以包含任意数量的对象,但没有对象将有超过31的属性值在子被发现。
note: my actual daysArray covers numbers as strings "1"-"31", and the courseHwork array of objects is dynamically populated so it can contain any number of objects, however no object will have a property value that exceeds "31" in the substring being found.
* 问:
我怎样才能通过两个数组的匹配值的两个阵列之间发现每一次循环,一个HTML元素被发现,还包含值完全相同,则已经附加的东西给它?的*
推荐答案
下面是想法,我想出了:
Here is idea i came up with:
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/
You can find it working here: http://jsfiddle.net/4cqCE/2/
好吧,看看如果你想要什么。首先,它会在2阵列相同的值,如果它发现它,它附加的东西div的含4在里面。这是你想要的吗?
Well, check if that what you want. First it looks for SAME value in 2 arrays, and if it finds it, it appends something to div containing "4" in it. Is that what you want?
下面是具有2相同的值,与2的div,每个包含的值的一个例子。
http://jsfiddle.net/4cqCE/3/
Here is an example with 2 same values, with 2 divs, each containing one of the value. http://jsfiddle.net/4cqCE/3/
这篇关于一个for循环比较两个数组寻找匹配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!