如何乘以html字符实体引用或?

时间:2016-12-21 17:40:42

标签: javascript html

我想在javascript中绘制一个带有函数的矩形,我需要将html字符实体引用 相乘以绘制两边之间的空格。 我可以将character entity reference保存在var上,然后像Python一样将其相乘吗?

function drawRectangle(side, figure){
        var spaces = " ";
        for (var i=0; i < side; i++) {
          document.write(figure);
        }
        for (var i=0; i< side-2; i++){
            document.write(figure + spaces*side + figure);
        }
        document.write("<br>");
        for (var i=0; i < side; i++) {
          document.write(figure);
        }
    }

2 个答案:

答案 0 :(得分:1)

使用.repeat()

function drawRectangle(side, figure){
  var spaces = "&nbsp;";
  for (var i=0; i < side; i++) {         
    document.write(figure);
  }
  for (var i=0; i< side-2; i++){
    document.write(figure + spaces.repeat(side) + figure);
  }
  document.write("<br>");
  for (var i=0; i < side; i++) {
    document.write(figure);
  }
}

注意:并非所有浏览器都支持此功能,因此您可以使用MDN提供的polyfill here

答案 1 :(得分:1)

&nbsp;不是标签。它是character entity reference.

字符串,而不是它。如果您处于支持它的环境中,则可以使用repeat功能。

&#13;
&#13;
var input = '&nbsp;';
var output = input.repeat(3);
console.log(output);
&#13;
&#13;
&#13;

如果您的环境支持它,您可以自己编写一个。

&#13;
&#13;
function repeatStr(str, count) {
  return new Array(count + 1).join(str);
}

var input = '&nbsp;';
var output = repeatStr(input, 3);
console.log(output);
&#13;
&#13;
&#13;

请注意,您should really avoid using document.write以及您尝试做的事情可能更容易使用CSS。

&#13;
&#13;
body {
  background: #000;
}
div {
  width: 100px;
  height: 100px;
  background: #0F0;
  /* This will move it to the right */
  margin-left: 4em;
}
&#13;
<div></div>
&#13;
&#13;
&#13;