[英]Unhandled Rejection (TypeError): Cannot read property 'push' of undefined
i am getting this error, i just want to make a function that return all indexes of an array, but i dont know if i doing something wrong, it just shows an error than push can not be used, becouse undefined value.我收到此错误,我只想创建一个返回数组所有索引的函数,但我不知道我是否做错了什么,它只是显示一个错误,而不是 push 无法使用,因为值未定义。
here the code:这里的代码:
function getIindex(array){
let values
for (let [ index, value ] of array.entries()) {
values.push(index)
console.log(values)
}
return values
}
let indexSubIndustry = getIindex(subRows)
You need to initialize the values
variable with a value, empty array in your case.您需要使用values
初始化values
变量,在您的情况下为空数组。
function getIindex(array){
let values = []; // here
for (let [ index, value ] of array.entries()) {
values.push(index)
console.log(values)
}
return values
}
let indexSubIndustry = getIindex(subRows)
You might need to specify type hint for that array, depending on your TS configuration (eg with strict mode enabled).您可能需要为该数组指定类型提示,具体取决于您的 TS 配置(例如启用严格模式)。
let values: number[] = [];
Btw your code can be simplified a lot, if you want to return keys of the array
parameter, just use keys()
method:顺便说一句,您的代码可以简化很多,如果您想返回array
参数的keys()
,只需使用keys()
方法:
function getIindex(array){
return [...array.keys()]; // convert iterator to array
}
You should assign your values as an empty array instead of keeping it undefined.您应该将您的值分配为一个空数组,而不是保持未定义。
let values = [];
// Rest of the code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.