如何从单个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
相关产品推荐
相关产品推荐

