[英]ReactJS: Unhandled Rejection (TypeError): Cannot read property 'push' of undefined
[英]Unhandled Rejection (TypeError): Cannot read property 'push' of undefined
我收到此錯誤,我只想創建一個返回數組所有索引的函數,但我不知道我是否做錯了什么,它只是顯示一個錯誤,而不是 push 無法使用,因為值未定義。
這里的代碼:
function getIindex(array){
let values
for (let [ index, value ] of array.entries()) {
values.push(index)
console.log(values)
}
return values
}
let indexSubIndustry = getIindex(subRows)
您需要使用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)
您可能需要為該數組指定類型提示,具體取決於您的 TS 配置(例如啟用嚴格模式)。
let values: number[] = [];
順便說一句,您的代碼可以簡化很多,如果您想返回array
參數的keys()
,只需使用keys()
方法:
function getIindex(array){
return [...array.keys()]; // convert iterator to array
}
您應該將您的值分配為一個空數組,而不是保持未定義。
let values = [];
// Rest of the code
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.