如果不允许使用 JOI npm 库,我们可以使用纯 JavaScript 来实现验证父数组。
以下是一个示例代码,用于验证一个父数组是否包含特定的子数组:
function validateParentArray(parentArray, childArray) {
// 遍历父数组
for (let arr of parentArray) {
// 检查子数组的长度是否相等
if (arr.length === childArray.length) {
let match = true;
// 遍历子数组的每个元素
for (let i = 0; i < arr.length; i++) {
// 检查元素是否相等
if (arr[i] !== childArray[i]) {
match = false;
break;
}
}
// 如果子数组匹配,则返回 true
if (match) {
return true;
}
}
}
// 如果父数组中没有匹配的子数组,则返回 false
return false;
}
// 用法示例
const parentArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const childArray = [4, 5, 6];
console.log(validateParentArray(parentArray, childArray)); // 输出 true
const parentArray2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const childArray2 = [1, 2, 3];
console.log(validateParentArray(parentArray2, childArray2)); // 输出 true
const parentArray3 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const childArray3 = [2, 3, 4];
console.log(validateParentArray(parentArray3, childArray3)); // 输出 false
在上述示例中,我们编写了一个名为 validateParentArray
的函数,它接收两个参数:父数组和子数组。该函数会遍历父数组,逐个与子数组进行比较。如果父数组中存在与子数组相等的子数组,则返回 true
,否则返回 false
。您可以根据自己的需求进行修改和扩展此函数。