刚才有个考试,里面需要用到push方法,然而在编译的时候报了push is not a function的错误,请问这是为啥?
/**
* @param {number[][]} edges
* @return {number}
*/
var treeDiameter = function (edges) {
if (edges.length === 0) return 0
let graph = {}
for (let i = 0; i < edges.length; i++) {
if (graph[edges[i][0]]) {
graph[edges[i][0]].push(edges[i][1])
} else {
graph[edges[i][0]] = [edges[i][1]]
}
if (graph[edges[i][1]]) {
graph[edges[i][1]].push(edges[i][0])
} else {
graph[edges[i][1]] = [edges[i][0]]
}
}
const res = []
let max = 0
const dfs = (cur, pre, path) => {
if (!graph[cur] || (graph[cur].length === 1 && graph[cur][0] === pre)) {
max = path.length > max ? path.length - 1 : max
return
}
for (let i = 0; i < graph[cur].length; i++) {
if (graph[cur][i] === pre) continue;
let next = graph[cur][i]
path.push(next)
dfs(next, cur, path)
path.pop()
}
}
for (let i = 0; i <= edges.length; i++) {
dfs(i, -1, [i])
}
return max
};
push是数组的方法,确定你使用push的对象是不是数组。
你代码怎么写的呢? 一般这样调用
var arr = [];
arr.push(5);
push是数组的方法,是用来追加元素的
a=[]
a.push('a')
a.push('b')
push是Array数组的方法,可能是你调用push的对象不是Array数组。