简体   繁体   中英

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!

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`);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM