简体   繁体   English

如何设置一个 arrays 的所有元素必须至少等于 JavaScript 中另一个数组的一个元素的条件?

[英]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.

相关问题 带有数组的数组:如何使用javascript将所有元素向前推送一个 - Arrays withing an array: how to push all elements forward by one with javascript 检查数组中的所有用户是否至少有一个 ID 等于 ID 数组的元素? - Check if all the users in an array have at least one element with an ID equal to an array of IDs? 如何识别一个数组的所有元素是否存在于另一个数组中 - Javascript How to identify if all elements of one array are present in another 如何知道一个字符串是否至少包含 Javascript 中的一个数组元素 - How to know if a string includes at least one element of array in Javascript MongoDB-查找元素,其中字段至少等于数组中的一个值 - MongoDB - Find elements, where field is equal to at least one value at array 在 JavaScript 中如何确保数组至少有一个特定元素而其他元素满足另一个条件? - In JavaScript how to make sure that array has at least one specific element and the others meet another condition? 设置一个元素宽度等于另一个 - Set one element width equal to another 如何使用javascript或angular将一个数组的每个元素添加到其他数组中的对应元素 - How can I add each element of one array to corresponding elements in other arrays with javascript or angular 在 arrays 的另一个数组中搜索一个数组的元素 - search for elements of one array in another array of arrays 检查数组中的所有内部 arrays 是否存在至少一个特定值(JavaScript) - Check if at least one specific value exists looking through all inner arrays in an array (JavaScript)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM