try this way :
var squares = [1, 2, 4, 8];
var cubes = [1, 4, 9, 16];
for(var i=0; i< squares.length; i++)
{
$('.' + getClass(squares[i], cubes[i])).doStuff();
}
문제
var squares = [1, 2, 4, 8];
var cubes = [1, 4, 9, 16];
var north,east,south,west;
north = getClass(squares[0], cubes[0]);
east = getClass(squares[1], cubes[1]);
south = getClass(squares[2], cubes[2]);
west = getClass(squares[3], cubes[3]);
$('.' + north).doStuff()
$('.' + east).doStuff()
$('.' + south).doStuff()
$('.' + west).doStuff()
I'm writing some code in javascript and it feels like I should be able to refactor this section but I don't know how to do it.
I think what I want to do is make north,east,south,west into some sort of collection so that i can iterate through it?
How would you recommend I do this with javascript?
해결책 2
try this way :
var squares = [1, 2, 4, 8];
var cubes = [1, 4, 9, 16];
for(var i=0; i< squares.length; i++)
{
$('.' + getClass(squares[i], cubes[i])).doStuff();
}
다른 팁
You could do something like that :
var squares = [1, 2, 4, 8];
var cubes = [1, 4, 9, 16];
var selectors = [];
for(var c = 0, c < squares.length, c++){
selectors.push(getClass(squares[c], cubes[c]));
}
$('.' + selectors.join(', .')).doStuff()
Alternatively, you could use .map
:
var squares = [1, 2, 4, 8];
var cubes = [1, 4, 9, 16];
var selectors = $.map(squares, function(_, i){
return getClass(squares[i], cubes[i]);
})
$('.' + selectors.join(', .')).doStuff()
Something like this:
var squares = [1, 2, 4, 8];
var cubes = [1, 4, 9, 16];
var direction=[]
for (i=0;i<cubes.length;i++){
a.push(getClass(squares[i], cubes[i]));
}
$(a).each(function (index) {
$('.' + this).doStuff();
});