[英]How to set up consition that all elements of one arrays must be equal to at least one element of the another array in JavaScript?
Transforming roman numerals into numbers, A user enter his one roman number.将罗马数字转换为数字,用户输入他的一个罗马数字。 and the code transfers his/her roman number into classic number.
代码将他/她的罗马号码转换为经典号码。
var roman = prompt("Enter roman number", roman);
var romandigits = roman.toString().split(""); // spliting roman number entered into an array!
let romannumerals = ["M", "D", "C", "L", "X", "V", "I"];
Now condition that suppose to be set is: ALL elements of the array romandigits have to be equal to AT LEAST one element of the array romannumerals!现在假设要设置的条件是:数组 romandigits 的所有元素必须至少等于数组 romannumerals 的一个元素!
You can create a set of romannumerals您可以创建一组罗马数字
let numeralSet = new Set(romannumerals);
Then you can check that each digit is in that set然后你可以检查每个数字是否在那个集合中
let badDigits = romanDigits.filter((c) => !numeralSet.has(c))
and then check whether there are any badDigits:然后检查是否有任何坏数字:
if (badDigits.length) {
console.error(`Invalid roman number ${roman} contains non-digits ${badDigits}`);
}
So putting it all together所以把它们放在一起
let roman = prompt("Enter roman number");
let romandigits = [...roman];
let romannumerals = ["M", "D", "C", "L", "X", "V", "I"];
let numeralSet = new Set(romannumerals);
let badDigits = romandigits.filter((c) => !numeralSet.has(c))
if (badDigits.length) {
console.error(`Invalid roman number ${roman} contains non-digits ${badDigits}`);
} else {
console.log(`${roman} is OK`);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.