2012-03-03 23 views
0

我想知道如何檢查一個有幾個變量的數組.. ..類似的東西。提前如何檢查數組中的數組? jquery

// Ignore the words in here, they are just there to explan. 
var $array = [ 
    alpha = { 
    name : $('.a'), 
    date : $('.b'), 
    street: $('.c') 
    }, 
    beta = { 
    name : $('.x'), 
    date : $('.y'), 
    street: $('.z') 
    }  
]; 

/* So now I got this arrays.. withing an array? is that correct? 
* or what is this called? 
* and now I want to check each object's length, if its 0 -> return false and 
* throw out an error, if >= 1 go on and check the next. */ 

// Check if all needed elements for the toggle to work are existent 
$.each($array, function(key, value) { 
    if (!value.length) { 
    alert("Could not find "+ '"' + value.selector +'"!') 
    return false 
    }; 
}); 
// Well obviously this doesnt work.. 

感謝: 我可以解釋與所示的代碼更好!

+4

你應該做研究和知道的** **的對象從** array ** – Joseph 2012-03-03 12:35:31

回答

1

你也可以遍歷一個object的屬性的名稱與for (... in ...)循環:

/* since the array isn't a jQuery object, don't prefix the name with `$` */ 
var things = [ 
    /* array elements have integer, not string, indices. In any case, 
     "alpha = ..." is the wrong syntax to set properties. What it 
     does is set a variable named "alpha". 
    */ 
    {...}, 
    {...}, 
]; 

$.each(things, function(idx, item) { 
    for (p in item) { 
    if (! item[p].length) { 
     /* alerts are disruptive; use other means of informing 
     the user or developer. 
     */ 
     //alert("Could not find "+ '"' + value.selector +'"!') 
     return false; 
    } /* blocks don't need semicolon separators */ 
    } 
}); 

參見「For .. in loop?

+0

這裏(p項)是什麼? – 2012-03-03 12:46:34

+0

@MartinBroder:這就是鏈接的用途。 – outis 2012-03-03 12:50:43

+0

也許應該在該循環中使用hasOwnProperty:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/HasOwnProperty – 2012-03-25 11:25:21