js 如何嵌套循环去判断只要有一个不满足就返回false

  const list = [
        {
          name: 'zs',
          details: [
            { value: 100, title: '语文' },
            { value: 99, title: '数学' },
            { value: 80, title: '英语' },
          ],
        },
        {
          name: 'lisi',
          details: [
            { value: 100, title: '语文' },
            { value: 0, title: '数学' },
            { value: null, title: '英语' },
          ],
        },
        {
          name: 'wangwu',
          details: [
            { value: 0, title: '语文' },
            { value: null, title: '数学' },
            { value: 80, title: '英语' },
          ],
        },
      ]

判断list里面details的value只要有一个为null或undefined 就验证为false
来个大佬实现一下快速高效简洁的方法

阅读 4.2k
6 个回答
list.every(r => r.details.every(r1 => r1.value||r1.value===0))

正则:

list.every(r => r.details.every(r1 => /^(0|[1-9][0-9]*)$/.test(r1.value)))
list.some(item=>item.details.some(v=>[undefined, null, 0].includes(v.value)))
新手上路,请多包涵

list.every(r => r.details.every(r => r.value))

list.every(r => r.details.every(r1 => r1.value != null))
const result = list.every(
    ({ details }) => details.every(
        ({ value }) => (value ?? null) !== null
    )
);

最里面那个条件可以改成 value !== undefined && value !== null

还可以用 flatMap 来实现,不过效率更低,因为要进行两次遍历,而且不能快速中断。

const result = list
    .flatMap(({ details }) => details.map(({ value }) => value))
    .every(value => (value ?? null) !== null);
JSON.stringify(list).indexOf(`"value":0`) > -1

我觉得这个最直观哈哈哈哈哈。额外注意的就是json化了以后,value会有双引号,会消除掉空格。当让格式化的时候也可以自己调整。

===== 差点儿忘了null之类的,用正则然后test也差不多可以 =====

是我扭不过来弯儿,还是咋这了,非要写出来

JSON.stringify(list, function(k,v){
    if(k === 'value' && !v) {
        return '淦'
    } 
    return v
}).indexOf("淦")
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题