Numbers triangle?

问题: I am new to programming still trying to apply for an IT academy and learning the basics. I am limited into using only arrays,strings,loops and conditions. I have been giv...

问题:

I am new to programming still trying to apply for an IT academy and learning the basics. I am limited into using only arrays,strings,loops and conditions.

I have been given a task to print a triangle from 1 to N and below. Example: 3

  1 
  1 2
  1 2 3 
  1 2 
  1

I used this:

var N = 2,
num = "";

for(var i=1; i<=N; i++)
{
  num = num + i
 console.log(num)}
 for(var j = num.length ; j = 1 ; j--){
 num = num.slice(0, -1)
  console.log(num);
 ;}

But it takes more than a second to do, could you please give me some tips on that I would deeply appreciate it!

Edit: Made the second loop right and all worked well. Thank you everybody for the help!


回答1:

You can create an array with n indices and then join then

const N = 3;

for (var i = (-1 * N) + 1; i < N; i++) {
  console.log(Array(N - Math.abs(i)).fill(0).map((i, j) => j + 1).join(' '));
}

//Or
for (var i = (-1 * N) + 1; i < N; i++) {
  console.log([...Array(N - Math.abs(i))].map((i, j) => j + 1).join(' '));
}


回答2:

A solution with only arrays (and array methods), strings, loops and conditions:

const N = 3;    
var nr = [];

for (i = 1; i <= N; i++){
  nr.push(i);
  console.log(nr.join(" "));
}

for (i = N; i > 0; i--){
  nr.pop();
  console.log(nr.join(" "));
}

Reading tip: https://www.w3schools.com/js/js_array_methods.asp

  • 发表于 2018-07-13 23:40
  • 阅读 ( 249 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除