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

如何从单个prompt输入中将多个整数存储到数组中?

解决方案

当然可行,只需要对输入的字符串做分割处理即可,修改后的代码如下:

const prompt = require('prompt-sync')();
const num_array = prompt("Enter x amount of integers: ").trim().split(' ');
console.log(num_array);

代码说明:

  • trim():去除输入字符串首尾的空格,避免用户输入前后空格导致数组出现空元素
  • split(' '):将字符串按空格分割成数组,每个空格分隔的内容会成为数组的一个独立元素

如果需要处理用户输入多个连续空格的情况,可以把split(' ')换成split(/\s+/),正则表达式\s+会匹配一个或多个空白字符(包括空格、制表符等),确保分割结果不会有空元素:

const prompt = require('prompt-sync')();
const num_array = prompt("Enter x amount of integers: ").trim().split(/\s+/);
console.log(num_array);

测试输入7 6 5 9 21 4 6 99 820,两种代码都会输出['7', '6', '5', '9', '21', '4', '6', '99', '820'],符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 22:34:52