我正在尝试实现递归函数,该功能返回每个对象中每个对象的特定属性值。每次迭代都会遇到对象或数组。
在将常规函数转换为递归函数时,我得到" arr.map不是函数错误"。
var arr = [{squares: Array(9), xIsNext: true, points: 10}, [{squares: Array(9), xIsNext: true, points: 0}, [{squares: Array(9), xIsNext: false, points: -10}]]];
非恢复:
function findObjPoints(arr){
return arr.map(isaObj) //works fine
}
function isaObj (j) {
if (j.points) {
return j.points;
} else {
return j; //returns an array
}
}
findObjPoints(arr)
递归:
function findObjPoints(arr){
return arr.map(isaObj) //arr.map is not a function error
}
function isaObj (j) {
if (j.points) {
return j.points;
} else {
return findObjPoints(j);
}
}
findObjPoints(arr)
错误消息:
VM245:2 Uncaught TypeError: arr.map is not a function
at findObjPoints (<anonymous>:2:15)
at isaObj (<anonymous>:10:14)
at Array.map (<anonymous>)
at findObjPoints (<anonymous>:2:15)
at isaObj (<anonymous>:10:14)
at Array.map (<anonymous>)
at findObjPoints (<anonymous>:2:15)
at <anonymous>:14:1
findObjPoints @ VM245:2
isaObj @ VM245:10
findObjPoints @ VM245:2
isaObj @ VM245:10
findObjPoints @ VM245:2
(anonymous) @ VM245:14
我缺少什么?
检查检查值是否具有"点"属性时,您正在以一种失败的方式进行j.points
的值(例如,当是0
(。
而不是:
测试 if (typeof j === "object" && "points" in j)
现在,当您的代码看到设置为零的"点"属性的第二个对象时,测试做出了错误的决定。
您应该检查值,以查看是否是Array.isArray()
的数组。如果是数组,则可以运行地图功能。
var arr = [{
squares: Array(9),
xIsNext: true,
points: 10
},
[{
squares: Array(9),
xIsNext: true,
points: 0
},
[{
squares: Array(9),
xIsNext: false,
points: -10
}]
]
];
function findObjPoints(arr) {
return Array.isArray(arr) ? arr.map(isaObj) : arr;
}
function isaObj(j) {
if (j.points) {
return j.points;
} else {
return findObjPoints(j);
}
}
findObjPoints(arr)
递归中的第二轮,isaobj返回findobjpoint(j(,其中j不是数组。因此,在FindObjpoint函数中,引发错误。