首页多横幅广告图轮播刷新随机出现undefined问题求助
问题原因
JavaScript数组默认从0开始计数,你当前给数组的1/2/3下标赋值,数组实际长度为4,下标0的位置是空值。随机数生成逻辑会生成0~3的整数,当随机数为0时就会读取到空值,出现undefined。
修正后的可用代码
直接替换你原有JS代码即可:
// 直接用数组字面量定义,自动从下标0开始赋值 var images = [ "<a href = 'https://www.paperage.com/clickthrough/Engineered-Buildings.html' target='_blank' rel='nofollow' ><img src='https://www.paperage.com/banners/Engineered-Buildings.gif' border='0' height='90' width='728' alt='Engineered Buildings'></a>", "<a href = 'https://www.paperage.com/clickthrough/ABB_reduce_sheet_break_frequency.html' target='_blank' rel='nofollow' ><img src='https://www.paperage.com/banners/ABB-Sheet-Break-Performance.jpg' border='0' height='90' width='728' alt='ABB'></a>", "<a href = 'https://www.paperage.com/clickthrough/Aspen_Technology_leader.html' target='_blank' rel='nofollow' ><img src='https://www.paperage.com/banners/Aspen-Technology-leader.jpg' border='0' height='90' width='728' alt='Aspen Technology Inc.'></a>" ]; // 数组长度为3,随机数范围0~2,刚好对应三个广告的下标 var index = Math.floor(Math.random() * images.length); document.write(images[index]);
可选修改方案
如果不想调整数组的定义结构,也可以只修改随机数生成逻辑,在原有计算结果后加1,保证随机数范围是1~3,也能解决问题:
index = Math.floor(Math.random() * images.length) + 1;
更推荐第一种数组字面量写法,符合前端开发的常规书写习惯,后续维护更方便。
内容的提问来源于stack exchange,提问作者Sports Guy
相关产品推荐
相关产品推荐

