[英]Jquery check if array 2 use all values array 1
我正在嘗試檢查array1是否使用我的array2的所有值,如果返回錯誤消息為假,但是我的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
所有元素時,單個String會存儲在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'
});
}
希望能幫助到你!
如果要檢查數組的每個元素是否在另一個數組中使用,則可能有兩種方法:
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
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.