Get the App
SLTechnology News&Howtos  ›  Development  › 

How to make rational use of cycle in JavaScript

Shulou Source: shulou.com Published: 2022-06-01 04:35:22 09月21日 Update

这篇文章主要介绍JavaScript如何合理使用循环,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

合理使用循环

如果多段代码实际上负责的是一些重复性的工作,那么可以用循环代替,使代码量更少。

// 判断是什么浏览器function getBrowser(){ const str = navigator.userAgent; if (str.includes('QQBrowser')) { return 'qq'; } else if (str.includes('Chrome')) { return 'chrome'; } else if (str.includes('Safari')) { return 'safri'; } else if (str.includes('Firefox')) { return 'firefox'; } else if(explorer.indexOf('Opera') >= 0){ return 'opera'; } else if (str.includes('msie')) { return 'ie'; } else { return 'other'; }};// 循环判断,将对应关系抽象为配置,更加清晰明确function getBrowser(){ const str = navigator.userAgent; const list = [ {key: 'QQBrowser', browser: 'qq'}, {key: 'Chrome', browser: 'chrome'}, {key: 'Safari', browser: 'safari'}, {key: 'Firefox', browser: 'firefox'}, {key: 'Opera', browser: 'opera'}, {key: 'msie', browser: 'ie'}, ]; for (let i = 0; i < list.length; i++) { const item = list[i]; if (str.includes(item.key)) {return item.browser}; } return 'other';}以上是"JavaScript如何合理使用循环"这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!

Tags: Loops code content articles value interests reality actually guys buddies more browsers knowledge industry information information channels repeatability channels references work Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Redmi Docker Shulou Information Xiaomi