我想用Javascript打印图案

时间:2016-07-11 12:27:37

标签: javascript

对于给定的数字N,使用JavaScript打印如下所示的网格,其中N为正数 整数大于2.

N = 3

的输出示例

1 1 1

1 0 1

1 1 1

N = 4

的输出示例

1 1 1 1

1 0 0 1

1 0 0 1

1 1 1 1

2 个答案:

答案 0 :(得分:0)

function printMatrix(n) {

  for (var i = 0; i<n; i++) {
  var x = "";
  	for (var j = 0; j <n; j++) {
      if (i == 0 || i == (n-1)) {
        x += "1";
      } else {
        if (j == 0 || j == (n-1) ) {
          x +="1";
        } else {
          x += "0";
        }
      }
    }
    $("#result").append(x + "<br>");
  }

}
$("#btn").click(function() {
  $("#result").empty();
printMatrix($("#index").val());  
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='number' id='index'>
<input type='button' value='print' id='btn'>
<div id="result">

</div>

即使你没有尝试任何东西,也有我的工作解决方案:

function printMatrix(n) {

  for (var i = 0; i<n; i++) {
  var x = "";
    for (var j = 0; j <n; j++) {
      if (i == 0 || i == (n-1)) {
        x += "1";
      } else {
        if (j == 0 || j == (n-1) ) {
          x +="1";
        } else {
          x += "0";
        }
      }
    }
    $("#result").append(x + "<br>");
  }

}

printMatrix(5);

您可以轻松改进

这里是JSFiddle

答案 1 :(得分:0)

显式循环太过分了;这是我使用ES6 Array.prototype.fill() method

组合的一些东西

let makeSquare = (size, hJoin="", vJoin="\n") => {
  let m = Array(size).fill(0, 1, size-1);
  m[0] = m[size-1] = 1;
  let s = Array(size).fill(m.join(hJoin), 1, size-1);
  s[0] = s[size-1] = Array(size).fill(1).join(hJoin);
  return s.join(vJoin);
};

console.log(makeSquare(5));
console.log(makeSquare(3, " "));
document.body.innerHTML = makeSquare(4, " ", "<br>");

浏览器支持可能会有所不同,因为 IE不支持.fill() ,但有一个.fill() polyfill ...

当然你不能填充箭头函数和函数参数默认值,但如果你关心旧的IE,你可以重写它们ES5样式:

var makeSquare = function(size, hJoin, vJoin) {
  if (hJoin === undefined) hJoin = "";
  if (vJoin === undefined) vJoin = "\n";
  var m = Array(size).fill(0, 1, size-1);
  m[0] = m[size-1] = 1;
  var s = Array(size).fill(m.join(hJoin), 1, size-1);
  s[0] = s[size-1] = Array(size).fill(1).join(hJoin);
  return s.join(vJoin);
};

Demo with polyfill that works in IE.