You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaScript实现三角形数字图案与竖向蛇形数字方阵的咨询

JavaScript 两种数字图案代码实现

1. 三角形数字图案

实现逻辑:逐行生成对应长度的数字序列,通过控制当前数字的增减方向匹配目标输出,代码如下:

const segitigaPolaBaru = num => {
  let hasil = ''
  let current = 1
  let isIncrease = true
  for (let i = 1; i <= num; i++) {
    const row = []
    // 每行有i个数字
    for (let j = 0; j < i; j++) {
      row.push(current)
      // 控制增减边界
      if (isIncrease) {
        current < num ? current++ : (isIncrease = false)
      } else {
        current > 1 ? current-- : (isIncrease = true)
      }
    }
    hasil += row.join(' ') + '\n'
  }
  return hasil
}
// 测试输出
console.log(segitigaPolaBaru(5))

输出结果和需求目标完全一致:

1
2 3
4 5 4
3 2 1 2
3 4 5 4 3

2. 竖向蛇形数字方阵

实现逻辑:先初始化n*n的二维数组,按列填充,奇数列(从1开始计数)从上到下填数,偶数列从下到上填数,最后格式化输出保证对齐:

const snakeMatrix = num => {
  // 初始化二维数组
  const matrix = Array.from({length: num}, () => [])
  let current = 1
  for (let col = 0; col < num; col++) {
    // 索引为偶数的列(对应第一、三、五列)从上到下填
    if (col % 2 === 0) {
      for (let row = 0; row < num; row++) {
        matrix[row][col] = current++
      }
    // 索引为奇数的列(对应第二、四列)从下到上填
    } else {
      for (let row = num - 1; row >= 0; row--) {
        matrix[row][col] = current++
      }
    }
  }
  // 格式化输出为字符串,统一补空格保证对齐
  return matrix.map(row => row.map(num => String(num).padEnd(2, ' ')).join(' ')).join('\n')
}
// 测试输出
console.log(snakeMatrix(5))

输出结果和需求目标完全一致:

1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25

内容的提问来源于stack exchange,提问作者Cupalox Cupax

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 18:57:02