Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Unsubscribed User
48,988 Pointshelp, how can i write this dry (math.random) ? Thnx !
$(document).ready(function(){
var $amaz_lg = [
'<iframe>...</iframe>',
'<iframe>...</iframe>',
'<iframe>...</iframe>'
];
$amaz_sm = [
'<iframe>...</iframe>',
'<iframe>...</iframe>',
'<iframe>...</iframe>'
];
$amaz_xs = [
'<iframe></iframe>',
'<iframe></iframe>',
'<iframe></iframe>'
];
var pickIframe = function(){
var item = $amaz_lg[Math.floor(Math.random() * 3)];
var item_b = $amaz_sm[Math.floor(Math.random() * 3)];
var item_c = $amaz_xs[Math.floor(Math.random() * 3)];
$("#jg_amaz_lg").append(item);
$("#jg_amaz_sm").append(item_b);
$("#jg_amaz_xs").append(item_c);
};
pickIframe();
});
1 Answer
Steven Parker
243,656 PointsThere's not much here to optimize, but you can eliminate defining and then calling a function that is not used again (pickIframe), and save a few variables and a little bit of code this way:
function pick1of3(arr) {
return arr[Math.floor(Math.random() * 3)];
}
$("#jg_amaz_lg").append(pick1of3($amaz_lg));
$("#jg_amaz_sm").append(pick1of3($amaz_sm));
$("#jg_amaz_xs").append(pick1of3($amaz_xs));
Also, unless you intended to make them globals, you may want to add "var" in front of the assignments of $amaz_sm and $amaz_xs.
Unsubscribed User
48,988 PointsUnsubscribed User
48,988 Pointsactually i had something in mind with a for loop but this works too and saves code, thank you