TypeScript报错:Cannot read properties of undefined (reading 'length') 求助
问题排查与改进建议
报错原因
你定义的函数getComputerChoice声明了参数x,这个参数会覆盖全局作用域里的同名数组x。当你调用这个函数时如果没有传入任何参数,函数内部的x就会变成undefined,此时访问x.length自然会抛出Cannot read properties of undefined (reading 'length')的错误。
修正方案
有两种可行的修正方式:
方式一:移除函数的参数
如果你的逻辑就是固定使用全局的['Rock','Paper','Scissors']数组,直接去掉函数的参数即可:
let x = ['Rock','Paper','Scissors']; function getComputerChoice(){ const random = Math.floor(Math.random() * x.length); console.log(x[random]); } // 调用函数 getComputerChoice();
方式二:调用函数时传入数组参数
如果希望函数更通用,能处理不同的选项数组,保留参数,但调用时必须传入有效的数组:
function getComputerChoice(x: string[]){ const random = Math.floor(Math.random() * x.length); console.log(x[random]); } // 调用时传入数组 getComputerChoice(['Rock','Paper','Scissors']);
额外改进建议
- 给变量和函数起更具语义的名字,比如把
x改成choices,这样代码可读性更强:const choices = ['Rock','Paper','Scissors']; function getComputerChoice(){ const randomIndex = Math.floor(Math.random() * choices.length); return choices[randomIndex]; // 建议返回结果而不是直接打印,让函数更灵活 } // 使用示例 const computerChoice = getComputerChoice(); console.log(computerChoice); - 可以给函数添加参数校验,避免传入非数组或空数组的情况:
function getComputerChoice(x: string[]){ if(!Array.isArray(x) || x.length === 0){ throw new Error('必须传入非空的数组'); } const random = Math.floor(Math.random() * x.length); return x[random]; }
内容的提问来源于stack exchange,提问作者Maya Strickland
相关产品推荐
相关产品推荐

