JavaScript中Cannot read property 'length' of undefined数组错误排查
解决Cannot read property 'length' of undefined数组错误
这个问题的核心原因很明确:你的shuffleArray函数大概率没有返回处理后的数组,导致执行checkColors = shuffleArray(checkColors)后,checkColors被赋值为undefined,后续访问它的length属性自然就抛出错误了。
为什么会这样?
JavaScript里如果函数没有显式写return语句,默认会返回undefined。如果你的shuffleArray是原地修改原数组(比如直接打乱传入的数组,但没return它),那赋值操作就会把checkColors变成undefined——这就是报错的根源。
解决方案步骤
1. 修复shuffleArray函数
先确保你的洗牌函数正确返回打乱后的数组,推荐使用标准的Fisher-Yates洗牌算法(效率高且无偏):
function shuffleArray(array) { // 复制原数组,避免修改原数组(可选,根据你的需求调整) const shuffled = [...array]; for (let i = shuffled.length - 1; i > 0; i--) { // 生成随机索引 const randomIndex = Math.floor(Math.random() * (i + 1)); // 交换元素 [shuffled[i], shuffled[randomIndex]] = [shuffled[randomIndex], shuffled[i]]; } // 关键:必须返回打乱后的数组 return shuffled; }
2. 优化你的业务代码
原代码里有一些冗余判断,同时可以补充过滤无效颜色值的逻辑(比如有时候css("color")会返回透明色rgba(0,0,0,0),这类值可能不是你需要的):
let checkColors = []; $("div[style]").each(function(){ const currentColor = $(this).css("color"); // 过滤掉无效/透明的颜色值 if(currentColor && currentColor !== 'rgba(0, 0, 0, 0)') { checkColors.push(currentColor); } }); // 洗牌后重新赋值(此时shuffleArray会返回数组,不会是undefined) checkColors = shuffleArray(checkColors); // 赋值颜色变量,逻辑更简洁 let backgroundColor, primaryColor, secondaryColor; if(checkColors.length >= 1) { backgroundColor = checkColors[0]; } if(checkColors.length >= 2) { primaryColor = checkColors[1]; } if(checkColors.length >= 3) { secondaryColor = checkColors[2]; }
额外提示
- 尽量用
let/const代替var,更符合现代JavaScript语法规范,避免变量提升带来的问题 - 原代码里的
if(checkColors)判断完全多余,因为checkColors初始就是数组,哪怕是空数组[]也是truthy值,不会进入假分支
内容的提问来源于stack exchange,提问作者Osman
相关产品推荐
相关产品推荐

