如何最小化我的JavaScript函数?

时间:2019-02-26 15:12:13

标签: javascript if-statement

我正在制作一个JavaScript函数,该函数从URL中获取某些内容并计算值。 此功能运行良好,但我想就如何用更少的代码最小化此功能获得一些反馈。现在看起来像这样混乱。

我非常感谢您的帮助。

代码:

getURL()
        {
            const myURL = this.blok.image;


                if (myURL != null)
                {
                    const split = myURL.split('/');

                    const array = split[5];

                    const split2 = array.split('x');

                    const height = split2[0];

                    const width  = split2[1];

                    const calc = width / height * 100;

                    alert(calc);
                }
                else {

                    return
                }
        }

2 个答案:

答案 0 :(得分:2)

您可以将这些拆分成一行,然后使用解构分配获得widthheight

const [width, height] = myURL.split("/")[5].split("x");

或使用RegEx:

const [width, height] = url.match(/\d+x\d+/)[0].split('x');

const url = `//a.storyblok.com/f/53830/6015x3900/7cea8305a6/mohit-singh-312892-unsplash.jpg`;

function getURL(myURL) {
  if (url != null) {
    const [width, height] = myURL.split("/")[5].split("x");
    const calc = (width / height) * 100;
    return calc;
  } else {
    return;
  }
}

const result = getURL(url);
console.log(result); 

/***********************/

const getUrl2 = url => {
  const [width, height] = url.match(/\d+x\d+/)[0].split('x')
  return (width / height) * 100;
}

const result2 = getUrl2(url);
console.log(result2)

答案 1 :(得分:1)

您可以使用正则表达式来获取两个数字,而不是拆分。比仅使用两个捕获组运行计算。

const path = "/foo/bar/30x100/world"
const nums = "/foo/bar/30x100/world".match(/(\d+)x(\d+)/)
const result = nums 
  ? Number(nums[1]) / Number(nums[2]) * 100
  : null
console.log(result)

您可以通过不使用太多变量来改善自己的水平

const split = myURL.split('/')[5].split('x');
const calc = Number(split[0]) / Number(split[1]) * 100;
console.log(calc);