const pyramidOfAsterisks = function(val) {
var arr=[];
for (let m = 1; m <= val; m ) {
if (m === 7)
break;
for (let s = 1; s <= val - m; s ) {
document.write("  ");
}
for (let n = 1; n <= m; n ) {
document.write("* ");
}
for (let p = 2; p <= m; p ) {
document.write("* ");
}
document.write("<br />");
arr.push()
}
}
var pyramid = pyramidOfAsterisks(12);
document.write(pyramid);
I have tried to display the output inside the given empty array., so i pushed the function into the array , but not displaying inside the array.
CodePudding user response:
- You never push anything to the array
arr
- You never return anything in
pyramidOfAsterisks
which is why it printsundefined
Replace document.write
with arr.push
and return arr
before the end of pyramidOfAsterisks
.
const pyramidOfAsterisks = function(val) {
var arr=[];
for (let m = 1; m <= val; m ) {
if (m === 7)
break;
for (let s = 1; s <= val - m; s ) {
arr.push("  ");
}
for (let n = 1; n <= m; n ) {
arr.push("* ");
}
for (let p = 2; p <= m; p ) {
arr.push("* ");
}
arr.push("<br />");
//arr.push()
};
return arr
}
//REM: Be aware of array.join
var pyramid = pyramidOfAsterisks(12);
document.write(pyramid.join(''));
CodePudding user response:
In the arr.push()
function input the value you want to add to the array.
For example
arr.push("one")
arr.push("two")
// It will return ["one","two"]
CodePudding user response:
const pyramidOfAsterisks = function(val) {
// var arr=[];
for (let m = 1; m <= val; m ) {
if (m === 7)
break;
for (let s = 1; s <= val - m; s ) {
document.write("  ");
}
for (let n = 1; n <= m; n ) {
document.write("* ");
}
for (let p = 2; p <= m; p ) {
document.write("* ");
}
document.write("<br />");
// arr.push()
}
}
var pyramid = pyramidOfAsterisks(12);
// document.write(pyramid);
This code works fine. It outputs undefined
because of the document.write in the end. pyramidOfAsterisks
does not return any value yet you assign the value it returns to a variable named pyramid, this is why pyramid
is equal to undefined