我正在尝试实现一个递归函数,它返回在嵌套的对象数组中找到的每个对象的特定属性值。每次迭代都会遇到一个对象或一个数组。
在将常规函数转换为递归函数时,我得到“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
我错过了什么?
答案 0 :(得分:1)
您应该使用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)
答案 1 :(得分:1)
当您检查正在检查的值是否有&#34;点&#34;属性,当j.points
的值为假(例如,0
时)时,您以失败的方式执行此操作。
相反,请测试:
if (typeof j === "object" && "points" in j)
就像现在一样,当你的代码看到第二个对象带有&#34; points&#34;属性设置为零,测试做出错误的决定。
答案 2 :(得分:0)
递归的第二轮,isaObj返回findObjPoint(j),其中j不是数组。因此在findObjPoint函数中,抛出错误。