![](/img/trans.png)
[英]How can I minimize a code function that finds repeated values in an array of objects in JavaScript?
[英]how can i minimize my javascript function?
我正在做一個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
}
}
您可以將這些拆分放到一行中,然后使用解構賦值獲得width
和height
:
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)
您可以使用正則表達式來獲取兩個數字,而不是拆分。 比僅使用兩個捕獲組運行計算。
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.