gpt4 book ai didi

javascript - 我怎样才能最小化我的javascript函数?

转载 作者:行者123 更新时间:2023-11-28 17:09:22 25 4
gpt4 key购买 nike

我正在制作一个 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
}
}

最佳答案

您可以将这些分割放在一行中并使用解构赋值来获取宽度高度:

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

或者使用正则表达式:

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)

关于javascript - 我怎样才能最小化我的javascript函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54888605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com