js封装图形的思想
我们可以把图形抽象成两个部分,整体看作是点和空格组成的,实际上是分为三段,然后一行一行的,然后作为整一个的数据,我们可以看为一个对象,点是一个数组,空格也是一个数组,因此封装函数,图形的规律,然后进行调用就可以了。
封装总的函数
//封装段
function dun(dunObj) {
let dunStr ="";
for (let i = 0; i < dunObj ; i++){
dunStr + = dunObj.char
}
return dunStr;
}
//封装行
function hang(hangArr) {
let hangStr="" ;
for (let i = 0; i < hangArr ; i++){
hangArr + = dun(hangArr[i]) ;
}
hangStr += "\n";
return hangStr;
}
//封装一个整体
function shape(shapeArr) {
let shapeStr="" ;
for (let i = 0; i < shapeArr ; i++){
shapeStr + = hang(shapeArr[i]) ;
}
shapeStr += "\n";
return shapeStr;
}
封装图形
//三角形
function trangle(high) {
let arr = [];
for (let i = 0; i < high; i++) {
let sizeNum = i;
arr.push([
{ char: " ", num: high - sizeNum - 1 },
{ char: "*", num: 2 * sizeNum + 1 },
])
}
return arr;
}
shape(trangle(8));
//直角三角形
function right_triangle(bottom) {
let arr = [];
for (let i = 0; i < bottom; i++) {
let sizeNum = i;
arr.push([
{ char: "*", num: sizeNum + 1 },
{ char: " ", num: bottom - sizeNum },
])
}
return arr
}
shape(right_triangle(4))
//矩形
function rectangle(bottom, high) {
let arr = [];
for (let i = 0; i < high; i++) {
arr.push([
{ char: "*", num: bottom },
])
}
return arr
}
shape(rectangle(4, 5));
//平行四边形
function parallelogram(bottom, high) {
let arr = [];
for (let i = 0; i < high; i++) {
let sizeNum = i;
arr.push([
{ char: " ", num: high - sizeNum },
{ char: "* ", num: bottom },
{ char: " ", num: sizeNum },
])
}
return arr
}
shape(parallelogram(2, 3))
//直角梯形
function trapezoid(bottom, high) {
let arr = [];
for (let i = 0; i < high; i++) {
let sizeNum = i;
arr.push([
{ char: "*", num: 2 * sizeNum + 2 },
])
}
return arr
}
shape(trapezoid(2, 3))
//等腰梯形
function Isosceles_trapezoid(bottom, high) {
let arr = [];
for (let i = 0; i < high; i++) {
let sizeNum = i;
arr.push([
{ char: " ", num: high - sizeNum },
{ char: "*", num: bottom + 2 * sizeNum },
{ char: " ", num: high - sizeNum },
])
}
return arr
}
shape(Isosceles_trapezoid(2, 3))
//菱形
function diamond(bottom) {
let hang = (bottom - 1) / 2 + 1;
let arr = [];
for (let i = 0; i < hang; i++) {
let sizeNum = i;
arr.push([
{ char: " ", num: (bottom - (2 * sizeNum + 1)) / 2 },
{ char: "*", num: 2 * sizeNum + 1 },
{ char: " ", num: (bottom - (2 * sizeNum + 1)) / 2 },
])
}
for (let i = 0; i < hang; i++) {
let sizeNum = i;
arr.push([
{ char: " ", num: sizeNum + 1 },
{ char: "*", num: (bottom - (2 * sizeNum + 1)) },
{ char: " ", num: sizeNum + 1 },
])
}
return arr
}
shape(diamond(8));