问题描述
我正在尝试用JavaScript制作Pascal的Triangle,但是有很多错误。我知道为什么会发生错误,但是有一些错误。
代码:
function triangle() {
this.rows = [[1]];
this.genRow = function() {
this.rows.push([]);
this.rows[this.rows.length-1].push(1);
for (var i = 0; i < this.rows[this.rows.length-1].length; i++){
var u = [this.rows[this.rows.length-1][i-1],this.rows[this.rows.length-1][i],this.rows[this.rows.length-1][i+1]];
var f = function(e) {
return e != undefined;
};
function s() {
var sum=0;
for (var index = 0; i < this.legnth; i++){
sum =+ this[i];
}
return sum;
}
u = u.filter(f).s();
this.rows[this.rows.length-1].push(u);
}
this.rows[this.rows.length-1].push(1);
}
}
var t = new triangle();
t.genRow();
console.log(t.rows);
谢谢。
解决方法
请尝试使用此代码,以使Pasqual的三角形出错
exports.loadCar= functions.https.onRequest((req,res) => {
// const requestedCar = Get requested car info from URL queries.
// Save requestedCar to Firestore DB,so it can be loaded in the html view.
// ... etc.
res.end();
});
我希望这段代码会有用。
谢谢。
,const pascalsTriangle = (rows = 1) => {
let res = [];
for (let i = 1; i <= rows; i++) {
if (i == 1) {
res.push([1]);
}
else if (i == 2) {
res.push([1,1]);
}
else {
let arr = [1];
let lastArr = res[i - 2];
for (let index=0; index<lastArr.length-1; index++) {
arr.push(lastArr[index] + lastArr[index + 1]);
}
arr.push(1);
res.push(arr);
}
}
return res;
};
这将完美地工作。您可以在这里参考。 https://github.com/omkarsk98/Exercism/blob/master/javascript/pascals-triangle/pascals-triangle.js
,这是JS中的一种方法。
function getNextLevel(previous) {
const current = [1];
for (let i = 1; i < previous.length; i++) {
current.push(previous[i] + previous[i - 1]);
}
current.push(1);
return current;
}
function pascalTriangle(levels = 1) {
let currentRow = [1];
while (levels--) {
console.log(currentRow.join(" "));
currentRow = getNextLevel(currentRow);
}
}
pascalTriangle(10);