仅在操作之间分隔

时间:2018-02-02 14:19:53

标签: javascript loops for-loop

我必须制作乘法表,对于n = 3看起来像这样:

1 x 1 = 1 | 1 x 2 = 2 | 1 x 3 = 3 
2 x 1 = 2 | 2 x 2 = 4 | 2 x 3 = 6 
3 x 1 = 3 | 3 x 2 = 6 | 3 x 3 = 9

现在我的代码看起来像这样:

var n = 3;
var result;

for (i = 1; i <= n; i++) {
    var result = '';
    for(j = 1; j <= n; j++) {
        result += ` ${i} * ${j} = ${i * j}`;
    }
    console.log(result);
}

我的结果是:

1 x 1 = 1  1 x 2 = 2  1 x 3 = 3 
2 x 1 = 2  2 x 2 = 4  2 x 3 = 6 
3 x 1 = 3  3 x 2 = 6  3 x 3 = 9

我不知道如何添加&#34; |&#34;仅在数学运算之间分开。如果我添加&#34; |&#34;在结果变量的末尾,我也会在最后一次操作后得到它,但我不想要它。

11 个答案:

答案 0 :(得分:5)

你可以追加|当它不是最后一行时到最后。

var n = 3;
var result;

for (i = 1; i <= n; i++) {
    var result = '';
    for(j = 1; j <= n; j++) {
        result += ` ${i} * ${j} = ${i * j}`;
        if(j != n)
        {
          result += ' |';
        }
    }
    console.log(result);
}

答案 1 :(得分:4)

您可以使用模运算符%j != n添加检查,以查看它是行的最后一部分,并根据该条件添加|

var n = 3;
var result;

for (i = 1; i <= n; i++) {
  var result = '';
  for (j = 1; j <= n; j++) {
    result += ` ${i} * ${j} = ${i * j}`;
    result += j % n ? ' |' : ''
  }
  console.log(result);
}

您可以使用Array.from()方法和join

执行此操作

var n = 4;

const result = Array.from(Array(n), (e, i) => {
  i += 1
  return Array.from(Array(n), (a, j) => {
    j += 1
    return `${i} * ${j} = ${i * j}` + (j != n ? ' | ' : '')
  }).join('')
}).join('\n')

console.log(result)

答案 2 :(得分:2)

您可以使用logical AND &&和字符串添加支票。它返回空字符串或分隔符。

var n = 3,
    result,
    i, j;

for (i = 1; i <= n; i++) {
    result = '';
    for (j = 1; j <= n; j++) {
        result += result && ' |';
        result += ` ${i} * ${j} = ${i * j}`;
    }
    console.log(result);
}

答案 3 :(得分:1)

不是将管道添加到每个项目的末尾,而是将其添加到除第一个项目之外的每个项目的开头更简单:

&#13;
&#13;
mgsub <- function(pattern, replacement, x, ...) {
  if (length(pattern)!=length(replacement)) {
    stop("pattern and replacement do not have the same length.")
  }
  result <- x
  for (i in 1:length(pattern)) {
    result <- gsub(pattern[i], replacement[i], result, ...)
  }
  result
}

isIsin <- function (identifier) {

  correctPrefix <- substr(identifier, 1, 2) %in% c(iso3166alpha2$Code, "XS")

  correctLength <- nchar(identifier) == 12  

  correctCharset <- !grepl('[[:punct:]]', identifier)

  if(!correctPrefix | !correctLength | !correctCharset) {
    return(FALSE)
  }

  # replace all character with its equivalent number  
  identifierOnlyNumbers <- mgsub(LETTERS, seq(10, 35), substr(identifier, 1, 11))

  # split the identifier in single digits and reverse its order
  characterVector <- rev(unlist(strsplit(identifierOnlyNumbers, "")))

  # Double every second digit of the group of digits with the rightmost character
  characterVector[seq(1, nchar(identifierOnlyNumbers), 2)] <- 
    as.character(as.numeric(characterVector[seq(1, nchar(identifierOnlyNumbers), 2)]) * 2)

  # Subtract 9 if > 9 (can apply to all since no digit can be greater than 9 before doubling)
  # Add up the digits
  summation <- sum(ifelse(as.numeric(characterVector) > 9, as.numeric(characterVector) - 9, as.numeric(characterVector)))

  # Take the 10s modulus of the sum, subtract it from 10 and take the 10s modulus of the result 
  # this final step is important in the instance where the modulus of the sum is 0, as the resulting check digit would be 10
  correctCheckDigit <- (10 - (summation %% 10)) %% 10 == as.numeric(substr(identifier, 12, 12))

  correctCheckDigit 

}
&#13;
&#13;
&#13;

答案 4 :(得分:1)

我可能会使用一些range函数(例如range(3, 7) //=> [3, 4, 5, 6, 7])然后map执行外部和内部范围,如下所示:

const range = (b, e) => Array.from({length: e - b + 1}, (_, i) => b + i)

const multTable = (m, n) => range(1, n).map(i => range(1, m).map(
  j => `${i} x ${j} = ${i * j}`
).join(' | ')).join('\n')

console.log(multTable(3, 3))

一旦您的产品或因素达到两位数,这将停止排队。如果这是一个问题,您可以将join(' | ')替换为join('\t|\t')。它不会是完美的,但它可能会更好。

答案 5 :(得分:0)

试试这个

var n = 3;
var result;

for (i = 1; i <= n; i++) {
   var result = '';
   for(j = 1; j <= n; j++) {
      if(j!=n)
         result += ` ${i} * ${j} = ${i * j}` + '|';
      else
         result += ` ${i} * ${j} = ${i * j}`;
   }

console.log(result);
}

答案 6 :(得分:0)

应该是:

var n = 3;
var result = '';

for (i = 1; i <= n; i++) {
    var result = '';
    for(j = 1; j <= n; j++) {
        result.length && result += '|';
        result += ` ${i} * ${j} = ${i * j}`;
    }
    console.log(result);
}

答案 7 :(得分:0)

对于所有n:

&#13;
&#13;
//google.com/?q=foo
&#13;
&#13;
&#13;

答案 8 :(得分:0)

只需使用数组收集结果,然后join部分|

&#13;
&#13;
var n = 3;
var result;

for (let i = 1; i <= n; i++) {
    result = [];
    for (let j = 1; j <= n; j++) {
        result.push(`${i} * ${j} = ${i * j}`);
    }
    console.log(result.join(' | '));
}
&#13;
&#13;
&#13;

答案 9 :(得分:0)

另一种方法是删除“|”的最后一次出现在slice()

的循环中

var n = 3;
var result;

for (var i = 1; i <= n; i++) {
  var result = '';
  for (var j = 1; j <= n; j++) {
    result += ` ${i} * ${j} = ${i * j} |`;
  }
  result = result.slice(0, -1);
  console.log(result)
}

答案 10 :(得分:0)

尝试

let n =3;
[...Array(n)].map((_,i,a)=>
  console.log(a.map((_,j)=>`${i+1} * ${++j} = ${(i+1)*j}`).join(' | ')));

let n =3;
[...Array(n)].map((_,i,a)=>console.log(a.map((_,j)=>`${i+1} * ${++j} = ${(i+1)*j}`).join(' | ')));