Conditional Statement in a map function with es6

2020-03-31 05:36发布

问题:

I nee to use the conditional statement in a map function

I am duplicating each single value of a path d in a SVG but i do not want this happening for the objects M and L of the array

Here is an example of the array as string.

M 175 0 L 326.55444566227675 87.50000000000001 L 326.55444566227675 262.5 L 175 350 L 23.445554337723223 262.5 L 23.44555433772325 87.49999999999999 L 175 0

This is an example to my case without the conditional statement

let neWd = array.map(x => { return x * 2; }).reverse().join(' ')

how can i write down this in e6 ? I don not want the multiplication happening for the elements L and M ( something like if x ? 'M' : 'L' return )

回答1:

I'm not sure why your using the reverse function also, reversing the svg path is slightly more complicated.

This code snippet doubles all the numbers, but leaves M and L intact.

In effect scaling up the svg path by 200%

var array = "M 175 0 L 326.55444566227675 87.50000000000001 L 326.55444566227675 262.5 L 175 350 L 23.445554337723223 262.5 L 23.44555433772325 87.49999999999999 L 175 0".split(" ");

let neWd = array.map(x => {
	if (x === 'M' || x === 'L'){
		return x;
	}else{
		return x * 2;
	}
}).join(' ')

console.log(neWd);



回答2:

Yes, just do it:

let neWd = array.map(x => {
    if (x == "M" || x == "L")
        return x; // unchanged
    else
        return String(parseInt(x, 10) * 2);
}).reverse().join(' ')