我有一个数组:
arr = [ 1, 2 , 3 ]
和另一个数组,其中我将DOM元素作为
Elem = [ 1, 3]
我需要在arr上进行迭代,只有在索引匹配的情况下才会这样做。例如,由于我有elem 1和3,当我循环通过arr时,某些事情应该只发生在1和3中,并且应该跳过2,因为没有elem 2。
有人告诉我要研究关联数组,我想知道如何用最少的行数来实现这一点。
我希望代码简单易懂,到目前为止,关联数组的所有示例都没有意义,而且臃肿不堪。
发布于 2014-04-26 04:51:41
for(var i = 0;i<arr.length;i++){
if(Elem.indexOf(arr[i])>-1){
//Elem contains arr[i] (contains object that at index i in arr)
//will be called only for 1 and 3 in arr
arr[i] = ... //do what you want with this object.
}
}
你是说这个吗?
发布于 2014-04-26 05:11:37
我对第二个数组做了一点修改,允许在一个地方定义多个操作。我不确定我是否正确地理解了你。
// array of DOM objects available
var arr = ['object1-selector', 'object2-selector', 'object3-selector'];
// array of actions with items that the method should be applied to
var actions = [
{
items: ['object1-selector', 'object3-selector'],
perform: function(elem) {
alert(elem);
}
},
{
items: ['object2-selector'],
perform: function(elem) {
alert(elem);
}
},
{
items: ['object4-selector'],
perform: function(elem) {
alert(elem);
}
}
];
//forEach loop that iterates over actions and checks if selector exists.
//If yes - it invokes the method
actions.forEach(function(action) {
action.items.forEach(function(item) {
if(arr.indexOf(item) > -1) {
action.perform(item);
}
});
});
如果您希望在一个地方定义操作,在多维数组中定义对象--请告诉我。我将试着调整这个例子。如果不存储选择器,而是存储整个DOM对象,只需修改items:
数组和循环,就可以检查元素是否存在。
哦,这是jsfiddle:http://jsfiddle.net/3WJxc/2/。jQuery仅用于警告()以显示工作示例。
发布于 2014-04-26 05:28:13
不太确定如何识别第二个数组中的元素,但这是我的建议。带有ids的数组
var arr = [ "id_1", "id_2", "id_3" ]
var Elem = {
"id_1": html_element,
"id_2": html_element,
"id_3": html_element
}
那你要做的就是
for( var i = 0; i < arr.length; i++ ) {
if( Elem[ arr[i] ] ) {
// do stuff
}
}
https://stackoverflow.com/questions/23311091
复制相似问题