jsÖÐÔõÑùÅжÏÊý×éΪ¿Õ
ÅжÏÊý×éÊÇ·ñΪ¿ÕµÄÒªÁ죺¼ì²éÊý×鳤¶È£¨ length ÊôÐÔΪ 0£©£»Ê¹Óà array.isarray() º¯Êý²¢¼ì²é³¤¶È£»Ê¹Óà every() »ò some() º¯Êý£»Ê¹Óà for…of Ñ»·¡£
ÔõÑùÔÚ JavaScript ÖÐÅжÏÊý×éΪ¿Õ£¿
ÅжÏÊý×éÊÇ·ñΪ¿ÕÔÚ JavaScript ÖкÜÊǼòÆÓ£¬¿ÉÒÔͨ¹ýÒÔÏÂÒªÁìʵÏÖ£º
1. ¼ì²éÊý×鳤¶È
Êý×éµÄ³¤¶ÈÊôÐÔ length ÌåÏÖÊý×éÖÐÔªËصÄÊýÄ¿¡£ÈôÊÇ length Ϊ 0£¬ÔòÊý×éΪ¿Õ¡£
const arr = []; if (arr.length === 0) { console.log("Êý×éΪ¿Õ"); }
µÇ¼ºó¸´ÖÆ
2. ʹÓà Array.isArray()
Array.isArray() º¯Êý¼ì²éÒ»¸ö¸ø¶¨ÖµÊÇ·ñÊÇÊý×é¡£ÈôÊÇÖµ²»ÊÇÊý×飬¸Ãº¯Êý½«·µ»Ø false¡£
const arr = []; if (Array.isArray(arr) && arr.length === 0) { console.log("Êý×éΪ¿Õ"); }
µÇ¼ºó¸´ÖÆ
3. ʹÓà every() ºÍ some()
every() º¯Êý¼ì²éÊý×éÖеÄÿ¸öÔªËØÊÇ·ñÖª×ã¸ø¶¨µÄÌõ¼þ¡£some() º¯Êý¼ì²éÊý×éÖÐÊÇ·ñÓÐÈκÎÔªËØÖª×ã¸ø¶¨µÄÌõ¼þ¡£
const arr = []; if (!arr.every((item) => item === undefined)) { console.log("Êý×鲻Ϊ¿Õ"); }
µÇ¼ºó¸´ÖÆ
const arr = []; if (!arr.some((item) => item !== undefined)) { console.log("Êý×éΪ¿Õ"); }
µÇ¼ºó¸´ÖÆ
4. ʹÓà for…of Ñ»·
for…of Ñ»·µü´úÊý×éÖеÄÿ¸öÔªËØ¡£ÈôÊÇÑ»·Ã»ÓÐÖ´ÐÐÈκεü´ú£¬ÔòÊý×éΪ¿Õ¡£
const arr = []; for (let item of arr) { // ´Ë´¦´úÂë²»»áÖ´ÐУ¬ÓÉÓÚÊý×éΪ¿Õ } console.log("Êý×éΪ¿Õ");
µÇ¼ºó¸´ÖÆ
ÒÔÉϾÍÊÇjsÖÐÔõÑùÅжÏÊý×éΪ¿ÕµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡