将数字转换为 space 的数量
Convert number into amount of space
我有一个数字,希望它生成一个对应 space
的字符串
例如:
var NumberOfSpace = 3;
// This will result in a string with 3 empty space
// the result will be " "
var space = convertToSpace(NumberOfSpace);
这是一个convertToSpace
函数
var convertToSpace = function (spaces) {
var string = "";
for (var i = 0; i < spaces; i++) {
string += " ";
}
return string;
}
您可以简单地使用 String.prototype.repeat
方法:
" ".repeat(3);
使用Array#fill
and Array#reduce
The fill()
method fills all the elements of an array from a start index to an end index with a static value
.
The reduce()
method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
var NumberOfSpace = 3;
function convertToSpace(param) {
return new Array(param).fill(' ').reduce(function(a, b) {
return a + b;
});
}
var space = convertToSpace(NumberOfSpace);
console.log(space);
一个简洁的选项:
function convertToSpace(n) {
return new Array(n + 1).join(' ')
}
我有一个数字,希望它生成一个对应 space
的字符串例如:
var NumberOfSpace = 3;
// This will result in a string with 3 empty space
// the result will be " "
var space = convertToSpace(NumberOfSpace);
这是一个convertToSpace
函数
var convertToSpace = function (spaces) {
var string = "";
for (var i = 0; i < spaces; i++) {
string += " ";
}
return string;
}
您可以简单地使用 String.prototype.repeat
方法:
" ".repeat(3);
使用Array#fill
and Array#reduce
The
fill()
method fills all the elements of an array from a start index to an end index with astatic value
.The
reduce()
method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
var NumberOfSpace = 3;
function convertToSpace(param) {
return new Array(param).fill(' ').reduce(function(a, b) {
return a + b;
});
}
var space = convertToSpace(NumberOfSpace);
console.log(space);
一个简洁的选项:
function convertToSpace(n) {
return new Array(n + 1).join(' ')
}