alexander janet alexander janet - 7 months ago 14
Javascript Question

Minimizing CSS "margin-" rules to one "margin:" rule with Javascript

I have entered each "margin-" CSS rule in an array giving me:

[ 'margin-left:15px', 'margin-right:25px', 'margin-top:100px' ]


I am trying to create an array that displays the values in the right order

var margRed1:[newMargTop, newMargRight, newMargBottom,newMargLeft];


My code is:

var directionRegex = /\d{2,3}px/;
var margRed = "margin: ";
var noMarg = "0px";
var margRed1 = [];

for (var i = 0; i < cssClassArrayMargin.length; i++) {
if (cssClassArrayMargin[i].match('-top')) {
var margTop = directionRegex.exec(cssClassArrayMargin[i]);
var newMargTop = margTop[0];
} else {
newMargTop = noMarg
}
if (cssClassArrayMargin[i].match('-right')) {
var margRight = directionRegex.exec(cssClassArrayMargin[i]);
var newMargRight = margRight[0];
} else {
newMargRight = noMarg
};
if (cssClassArrayMargin[i].match('-bot')) {
var margBot = directionRegex.exec(cssClassArrayMargin[i]);
var newMargBot = margBot[0];
} else {
newMargBot = noMarg
}
if (cssClassArrayMargin[i].match('-left')) {
var margLeft = directionRegex.exec(cssClassArrayMargin[i]);
var newMargLeft = margLeft[0];
} else {
newMargLeft = noMarg
}
}
if (newMargTop || newMargRight || newMargBot || newMargLeft === undefined) {
newMargTop = noMarg;
newMargBot = noMarg;
}

console.log(margRed1)


It gives me the following array:

[ '100px', '25px', undefined, '15px' ]


I do not understand why it does not display 0px and instead displays undefined.

Thanks

Answer

why don't you try to initial this "margRed1" array like this first?

var margRed1 = [ '0px', '0px', '0px', '0px' ];

and then remove these code

if (newMargTop || newMargRight || newMargBot || newMargLeft === undefined) {
   newMargTop = noMarg;
   newMargBot = noMarg;
}