gpt4 book ai didi

javascript - Jquery 检查数组 2 是否使用数组 1 的所有值

转载 作者:行者123 更新时间:2023-11-28 01:28:19 25 4
gpt4 key购买 nike

我正在尝试检查 array1 是否使用我的 array2 的所有值,如果 false 返回错误消息,但我的 array1.length 不等于 array2.length,我正在寻找几个小时来了解原因。有人能帮我吗?如果问题不是出自那里,谁能告诉我我的错误?

function controlUserInput(inputText, appLang) {
const regex = /\$[^$]*\$/gm;
const str = $('#formulaire-preview-textarea').val();
let m;
var array = populateVariable(appLang);

while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
var isEqual = match.length==array.length;
// for (i=0; i<=array.length-1;i++){
if(displayCpt == 4 && isEqual && Array.from(match).every(function(paramInMatch){
return $.inArray(paramInMatch, array) != -1;
})){
osapi.jive.core.container.sendNotification({
"message": "Toutes les valeurs rentrées sont correctes",
"severity": "success"
});
}else{
osapi.jive.core.container.sendNotification({
"message": "Vous n'avez pas utilisé toutes les valeurs",
"severity": "error"
});
}
// }
})
};
}

最佳答案

编辑:

当您尝试遍历 m 的所有元素时,单个字符串存储在 match 中,因此当您尝试与 array< 进行比较时 它失败了。

不是遍历 m 的所有元素,解决方案是:

if (
m.length === array.length &&
m.every(el => array.includes(el))
) {
osapi.jive.core.container.sendNotification({
message: 'Toutes les valeurs rentrées sont correctes',
severity: 'success'
});
} else {
osapi.jive.core.container.sendNotification({
message: "Vous n'avez pas utilisé toutes les valeurs",
severity: 'error'
});
}

希望对您有所帮助!

原始答案

如果你想检查一个数组的每个元素是否在另一个数组中使用,你可能有两种方法:

Arr2 是 Arr1 的子集

const arr1 = [1, 2, 3, 4, 5, 6];
const arr2 = [1, 2, 5, 6];

function isSubSet(subSet, wholeSet) {
return subSet.every(el => wholeSet.includes(el));
}

console.log(isSubSet(arr2, arr1)); // returns true

Arr2 包含 Arr1 的所有元素

const arr1 = [1, 2, 3, 4, 5, 6];
const arr2 = [1, 2, 5, 6];
const arr3 = [1, 2, 5, 6, 3, 4];

function isWholeSet(subSet, wholeSet) {
return (
subSet.length === wholeSet.length &&
subSet.every(el => wholeSet.includes(el))
);
}

console.log(isWholeSet(arr2, arr1)); // returns false
console.log(isWholeSet(arr3, arr1)); // returns true

关于javascript - Jquery 检查数组 2 是否使用数组 1 的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51127276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com