我为此标准的日常作业问题编写了解决方案,以递归方式解决Pascal的Triangle。 Console.log显示我的函数得出的答案。打印到div的innerHTML会将答案写入屏幕。逐步浏览chrome中的javascript调试器会显示解决方案数组在返回returnArray之前就存在。但是仍然在一天结束时,该函数返回“ undefined”。我不明白。
var generate = function (numRows) {
var startRow = 1;
var startCol = 1;
var endRow = parseInt(numRows);
var rowArray = [];
var returnArray = [];
var triVal;
var triangle = function (row, col) {
//base case
if (col == 1 || col == row) { //If the element is the either first or last element then initialize it with 1
if (col == 1) {
rowArray = [];
}
triVal = 1;
rowArray.push(triVal);
if (col == row) {
returnArray.push(rowArray);
}
}
else {
//calc
triVal = returnArray[row - 2][col - 2] + returnArray[row - 2][col - 1]
triVal = typeof (triVal) === "undefined" ? 1 : triVal;
rowArray.push(triVal);
}
if (col == row && row == endRow) { //stop the function and return
console.log(JSON.stringify(returnArray));
myDiv2.innerHTML = JSON.stringify(returnArray);
return returnArray;
}
else {
if (col == row) {
col = 1;
row = row + 1;
} else {
col = col + 1;
}
triangle(row, col);
}
}
triangle(startRow, startCol);
};
var test = generate(4);
console.log('test is: ' + test); //Why does it returned undefined
我的第一个解决方案是使用形式函数generate(numRows){};但作业要求解决方案采用表达式形式var generate = function(numRows){};第一种方法返回我的预期结果。第二个没有。我不了解javascript的什么基础?
答案 0 :(得分:0)
var generate = function (numRows) {
//numRows == 0 ? numRows = 1 : numRows = numRows;
if (numRows == 0) { return [];}
var startRow = 1;
var startCol = 1;
var endRow = parseInt(numRows);
var rowArray = [];
var returnArray = [];
var triVal;
var triangle = function (row, col) {
//base case
if (col == 1 || col == row) { //If the element is the either first or last element then initialize it with 1
if (col == 1) {
rowArray = [];
}
triVal = 1;
rowArray.push(triVal);
if (col == row) {
returnArray.push(rowArray);
}
}
else {
//calc
triVal = returnArray[row - 2][col - 2] + returnArray[row - 2][col - 1]
triVal = typeof (triVal) === "undefined" ? 1 : triVal;
rowArray.push(triVal);
}
if (col == row && row == endRow) { //stop the function and return
console.log(JSON.stringify(returnArray));
myDiv2.innerHTML = JSON.stringify(returnArray);
return returnArray;
}
else {
if (col == row) {
col = 1;
row = row + 1;
} else {
col = col + 1;
}
triangle(row, col);
}
}
triangle(startRow, startCol);
return returnArray; //duh...the obvious answer!!!
};
var test = generate(1);
console.log('test is: ' + (JSON.stringify(test)));