javascript - 如何将此 else if 语句转换为 switch 语句?
问题描述
我创建了一个函数来每秒检查网站的当前 url 并根据某个值字符串更改 HTML 元素中的元标记图像。我的代码很完美,但是我想让我的代码更具可读性 7 优化......所以我想把这段代码变成 switch 语句,但我现在无法自己弄清楚。任何帮助将不胜感激。这是代码:
// Variable declarations
var imgOgSrc = $('meta[property="og:image"]');
var twitterImgSrc = $('meta[name="twitter:image:src"]');
var currentUrl;
// Checks for current url & changes meta tags depending on slug value
function getCurrentUrl(){
currentUrl = window.location.href;
if(currentUrl.toLowerCase().indexOf('python') >= 0) {
imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
} else if (currentUrl.toLowerCase().indexOf('java') >= 0) {
imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
} else if (currentUrl.toLowerCase().indexOf('php') >= 0) {
imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
}
else {
imgOgSrc.attr('content', currentUrl);
twitterImgSrc.attr('content', currentUrl);
}
}
解决方案
python
您可以为,java
和php
withimgOgSrc
和twitterImgSrc
properties取一个对象,并null
为不匹配的 URL 使用一个属性。
function getTarget(url) {
const targets = {
python: {
imgOgSrc: 'data1',
twitterImgSrc: 'data2'
},
java: {
imgOgSrc: 'data3',
twitterImgSrc: 'data4'
},
php: {
imgOgSrc: 'data5',
twitterImgSrc: 'data6'
},
null: { // default values
imgOgSrc: 'data7',
twitterImgSrc: 'data8'
}
};
return targets[url.toLowerCase().match(new RegExp(Object.keys(targets).join('|')))];
}
console.log(getTarget('blablajavabla'));
console.log(getTarget('blablabla'));
推荐阅读
- java - 如果源对象中的字段不为空,MyBatis 会更新
- ios - 如何在 swift 4.2 中增加 UICollectionview 单元格大小等于屏幕大小?
- python - 循环内的 if 函数内的语法错误
- c++ - 从 c++ CLR/CLI 项目的资源文件加载图像
- yosys - 奇怪的 RTL 输出
- c++ - 如何创建一个新向量,其中每个元素都必须从许多向量中计算出来?
- java - 使用netty获取客户端的SSL证书
- sql-server - 在 SQL Server 存储过程中查找当前时间之前最接近的值
- android - What does "support" refer to in Android?
- javascript - 如何使用观察者模式?