let num = prompt("enter a number");
let foo = num.split("").map(item => parseInt(item, 10));
let fig = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let arr = [
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine"
];
fig[0] = arr[0];
fig[1] = arr[1];
fig[2] = arr[2];
// let filteredNum = foo.filter(number => fig.includes(number));
// console.log(filteredNum);
// console.log(fig[0]);
// console.log(fig[1]);
// console.log(fig[2]);
我需要帮助,我有一组数字(0 - 9)。我提示用户输入一个数字,这样当用户输入1时,它打印出一个字符串'one',如果用户输入34,则打印出三个字符串。
答案 0 :(得分:2)
您可以尝试以下
let num = prompt("enter a number");
let foo = num.split("").map(item => parseInt(item, 10));
let arr = ["zero","one","two","three","four","five","six","seven","eight","nine"];
console.log(foo.reduce((a,c) => a + " " + arr[c], ""));
请注意,不需要fig
,因为您已经有arr
的索引来匹配字符串的数值
答案 1 :(得分:0)
您可以将您的数字转换为字符串并将对象用作字典:
const num = prompt("enter a number");
const dict = {
"0": "zero",
"1": "one",
"2": "two",
"3": "three",
"4": "four",
"5": "five",
"6": "six",
"7": "seven",
"8": "eight",
"9": "nine"
}
const res = `${num}`.split('').map(e => dict[e]).join(' ');
console.log(res);
答案 2 :(得分:0)
我认为这里不需要reducer
。这是一个简单的逻辑,也可以使用一个简单的循环来实现。
let num = prompt("enter a number");
let foo = num.split("").map(item => parseInt(item, 10));
let arr = ["zero","one","two","three","four","five","six","seven","eight","nine"];
var inputStr = '';
foo.forEach((num)=>{
inputStr += arr[num] + ' ';
});
console.log(inputStr);
或者您甚至可以使用这样的单线:
let num = prompt("enter a number");
let arr = ["zero","one","two","three","four","five","six","seven","eight","nine"];
let foo = num.split("").map(item => arr[parseInt(item, 10)]).join(' ');
console.log(foo);
答案 3 :(得分:0)
您可以使用Array.from
获取单个数字(字符串作为可迭代)并映射该字词(如果存在)。如果没有取值。
稍后用空格加入数组。
var numbers = prompt("enter a number"),
array = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
console.log(Array.from(numbers, i => array[i] || i).join(' '));

答案 4 :(得分:0)
您需要检查字符串是否为数字?
const num = prompt("enter a number");
const arr = [ "zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine" ];
let foo = [];
if(!isNaN(num)) {
foo = num.split('').map(n => arr[n]).join(' ');
}
console.log(foo);
答案 5 :(得分:0)
console.log(prompt("enter a number").split``.map(_ => ~~_).reduce((_, i) => `${_} ${"zero one two three four five six seven eight nine".split` `[i]}`, ``));
这使用map
和reduce
console.log( /*begin console.log*/
prompt( /*take input*/
'enter a number'. /*input text*/
split``. /*split at every single char*/
map( /*map over all elements of the array*/
_ => ~~_). /*convert to number and reduce to integer*/
reduce( /*begin reducing the array to one value*/
(_,i)=> /*parameters*/
`${_} ${'zero one two three four five six seven eight nine'.split` `[i]}`
, ''))
// the last part writes value of _ and then creates a string (0-9) and splits at
//space and then selects the value depending on i