I have simple JS(jquery) code and I would like to run it through all three nested arrays. Now it only executes first nested array ([16, 10, 11) and then stops . I have read that "for" loop may work, but I tried and failed :[
Is any1 capable of solving this problem? I will be grateful!
$(function(){
var cat = [[16, 10, 11],[15, 10, 11],[36, 10, 11]];
$('li#hcategory_' + cat[0][0] + ' ul.level2 > li:gt(' + cat[0][1] +')').hide();
var l = $('li#hcategory_' + cat[0][0] + ' .level2 > li').length;
if (l > cat[0][2]) {
$('li#hcategory_' + cat[0][0] + 'span.show_more_button').show();
} else {
$('li#hcategory_' + cat[0][0] + 'span.show_more_button').hide();
}
$('li#hcategory_16 .show_more_button').click(function () {
$('li#hcategory_' + cat[0][0] + ' ul.level2 > li:gt(' + cat[0][1] +')').show('slow');
});
});
You could use Array#forEach()
for iterating.
The
forEach()
method executes a provided function once per array element.
$(function () {
var cat = [[16, 10, 11], [15, 10, 11], [36, 10, 11]];
cat.forEach(function (c) {
$('li#hcategory_' + c[0] + ' ul.level2 > li:gt(' + c[1] + ')').hide();
var l = $('li#hcategory_' + c[0] + ' .level2 > li').length;
if (l > c[2]) {
$('li#hcategory_' + c[0] + 'span.show_more_button').show();
} else {
$('li#hcategory_' + c[0] + 'span.show_more_button').hide();
}
$('li#hcategory_16 .show_more_button').click(function () {
$('li#hcategory_' + c[0] + ' ul.level2 > li:gt(' + c[1] + ')').show('slow');
});
});
});
You can use a double nested forEach()
method first for the main array and the second for each nested array like such:
var cat = [[16, 10, 11],[15, 10, 11],[36, 10, 11]];
cat.forEach(function(v,i){
//here v represents the values of the first level,
//assuming it contains only arrays you can run a nested
console.log(v);
v.forEach(function(vv, ii){
// here you can access booth arrays respectively calling them
console.log(v);
conosole.log(vv);
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.