如何基于数组随机值实现网站跳转?
解决方案
首先你需要建立城市与对应目标网址的映射关系,用对象存储是最直观的方式,之后就能根据随机选中的城市,取出对应的网址完成跳转。修改后的代码如下:
// 建立城市和对应网址的键值对映射 const cityUrls = { "Bhutan": "https://example.com/bhutan", "London": "https://example.com/london", "Paris": "https://example.com/paris", "Dubai": "https://example.com/dubai", "New York City": "https://example.com/new-york", "Singapore": "https://example.com/singapore" }; // 获取所有城市名称的数组 const cities = Object.keys(cityUrls); // 随机选中一个城市 const selectedCity = cities[Math.floor(Math.random() * cities.length)]; function myCities() { // 根据选中的城市匹配对应网址 const targetUrl = cityUrls[selectedCity]; // 确认网址存在后跳转,避免无对应值的错误 if (targetUrl) { location.assign(targetUrl); } }
补充说明:
- 用对象存储映射比单独的城市数组更易维护,能直接关联城市和网址
- 如果你需要每次调用
myCities函数时都重新随机选择城市,把随机逻辑移到函数内部即可:
const cityUrls = { "Bhutan": "https://example.com/bhutan", "London": "https://example.com/london", "Paris": "https://example.com/paris", "Dubai": "https://example.com/dubai", "New York City": "https://example.com/new-york", "Singapore": "https://example.com/singapore" }; function myCities() { const cities = Object.keys(cityUrls); const selectedCity = cities[Math.floor(Math.random() * cities.length)]; const targetUrl = cityUrls[selectedCity]; if (targetUrl) { location.assign(targetUrl); } }
内容的提问来源于stack exchange,提问作者Maicky Perez
相关产品推荐
相关产品推荐

