将 'prompt()' 的结果拆分为数组中的项目?

Split result of 'prompt()' into items in an array?

问题

如何仅使用一个值即可将多个值添加到列表中?prompt();

代码

let items = [];
action = prompt("Enter");

如果我的输入是 Hello World!,那么我怎样才能使我的列表看起来像这样:

items = ["Hello", "World!"];

尝试次数

这是我能得到的最接近的(它失败了,因为我只能使用一个prompt();):

let first = prompt("Enter 1");
let second = prompt("Enter 2");
items.push(first);
items.push(second);

您可以拆分接收到的字符串以获得具有两个单独值的数组

let action = prompt();
let items = action.split(' ');

console.log(items);

通过指定 whitespace 作为分隔符来使用 String.split

The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.

例如:

let inputFromPrompt = prompt("Enter"); 
// then enter "Hello World!"
let token = inputFromPrompt.split(' ');

你的预期结果是这样的?

let items = [], action, i = 1;
  
while(action = prompt(`Enter ${i++}`)){
   items = items.concat(action.split(" "));
}
  
console.log(items);

//Enter 1: hello world
//Enter 2: four five
//[Cancel] prompt

//Result: ["hello", "world", "four", "five"]

.split(" ") : 用 space

分隔单词

.concat(items) : 将当前数组与前一个数组合并