亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何訪問嵌套數組/對象并過濾數組的非空元素,如 NaN、null、0

如何訪問嵌套數組/對象并過濾數組的非空元素,如 NaN、null、0

ABOUTYOU 2022-06-16 10:57:39
下面是對象數組。我們要做的是創建一個數組,其中包含數組 arr 的所有非空元素,其值不等于 null、NaN、'undefined' 和 0留在第二個數組中var arr = [  { id: 15 },  { id: -1 },  { id: 0 },  { id: 3 },  { id: 12.2 },  {},  { id: null },  { id: NaN },  { id: "undefined" }];我試過的是var obj1 = {}; var prop1 = []; var prop2 = [];  arr.forEach(el=>{      if(el.id!==0 || el.id!==null || el.id!==undefined || el.id!==NaN){          prop1.push(el)      }      else{          prop2.push(el)      }  })  console.log(prop1)    console.log(prop2)但它不工作我收到的輸出 -1] [{id: 15}, {id: -1}, {id: 0}, {id: 3}, {id: 12.2}, {}, {id: null}, {id: null}, { ID:“未定義”}]2] []預期的 -1] [{id:0},{id:null},{id:“未定義”}]2] [{id:15},{id:-1},{id:3},{id:12.2}]
查看完整描述

3 回答

?
呼如林

TA貢獻1798條經驗 獲得超3個贊

您可以轉換為 boolean ( !el.id) 這將處理大多數情況,您必須"undefined"單獨處理:


var arr = [

  { id: 15 },

  { id: -1 },

  { id: 0 },

  { id: 3 },

  { id: 12.2 },

  {},

  { id: null },

  { id: NaN },

  { id: "undefined" }

];


var obj1 = {};

 var prop1 = [];

 var prop2 = [];

  arr.forEach(el=>{

      if(!el.id || el.id === "undefined"){

          prop1.push(el)

      }

      else{

          prop2.push(el)

      }

  })


  console.log(prop1);

  console.log(prop2);

  console.log(prop1.length);

  console.log(prop2.length);


查看完整回答
反對 回復 2022-06-16
?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

嘗試這個:


var arr = [

  { id: 15 },

  { id: -1 },

  { id: 0 },

  { id: 3 },

  { id: 12.2 },

  {},

  { id: null },

  { id: NaN },

  { id: "undefined" }

];

let filterArray = arr.filter((el) => {return !el.id || [0,null,"undefined",NaN].includes(el.id)});

console.log(filterArray);

let filterArray1 = arr.filter((el) => {return el.id && ![0,null,"undefined",NaN].includes(el.id)});

console.log(filterArray1);


查看完整回答
反對 回復 2022-06-16
?
月關寶盒

TA貢獻1772條經驗 獲得超5個贊

為什么它不起作用?是順序不正確還是有 JavaScript 錯誤?

代碼乍一看很好,您可以使用 if (!el.id),它檢查 id 是否為“假”(0,null,undefined,NaN,false)

您還可以查看“map”和“filter”方法, https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/map


查看完整回答
反對 回復 2022-06-16
  • 3 回答
  • 0 關注
  • 205 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號