验证数组数组

时间:2021-03-19 00:31:30

标签: javascript arrays

可以像这样验证数组:

const Array = [[1, 2], ['hello', 'hi'], []]

当一个数组为空或为“.length === 0”时,我需要权衡,但只有当数组之一为空时,它才会说一个错误,如果所有数组都为空,则是相同的错误。

例如这是一个错误

const Array = [[1, 2], ['hello', 'hi'], []]
const Array = [[1, 2], [], []]
const Array = [[], ['hello', 'hi'], []]

当所有数组都有值时,执行其他操作,例如显示警报

5 个答案:

答案 0 :(得分:1)

您可以使用 .some() 函数检查数组中的一项或多项是否符合特定条件。以下是应用于您的特定案例的情况:

const array_of_arrays = [[1, 2], ['hello', 'hi'], []]

let contains_empty_arrays = array_of_arrays.some((sub_array) => sub_array.length === 0)

console.log(contains_empty_arrays )

答案 1 :(得分:1)

使用 Array.prototype.every()

const data = [[], ["hello", "hi"], []],
  check = data.every(item => item.length);
if (!check) {
  alert("Empty Values");
}

答案 2 :(得分:0)

你可以这样做。

const myArray = [[1, 2], ['hello', 'hi'], []];

if (myArray.find((innerArray) => innerArray.length === 0)) {
  console.log("Some error")
} else {
  console.log("Do something else");
}

答案 3 :(得分:0)

能否请您尝试运行以下代码段:

const myArray = [[1, 2], ['hello', 'hi'], []];

var with_empty = false;

for (i = 0; i < myArray.length; i++) {

  if(myArray[i].length == 0){
    with_empty = true;
    break;
  }

}

if(with_empty)
  alert('There is an empty value!');

答案 4 :(得分:0)

也许你想做这样的事情:

function fullNest(arrayOfArrays){
  for(let a of arrayOfArrays){
    if(!a.length){
       return false;
     }
   }
   return true;
}
const nest = [[1, 2], ['hello', 'hi'], []];
console.log(nest); console.log(fullNest(nest)); console.log('-'.repeat(50)); 
nest[2].push('full now'); console.log(nest); console.log(fullNest(nest));

相关问题