js遞歸遍歷數組並判斷數組中的每一項如果都不為空則返回true,只要有一項為空則返回false。一開始看到這樣的場景我就覺得很簡單沒難度,可真正上手才發現並不那麼簡單,而且想要讓代碼健壯就又複雜了些。於是經過一個小時的努力加不斷修改、增補,總算實現了自己想要的一個方法。
代碼如下:
const isArrayEmpty = arr => {
if (!Array.isArray(arr) || !arr.length) {
return false
}
let flag = true
const recurse = arr => {
for (const node of arr) {
if (Array.isArray(node)) {
// node為[[]]或[[[]]]的情況會走這裏
if (!node.length) {
flag = false
break
} else {
recurse(node)
}
} else {
// node是null或undefined則str就等於node,否則str就等於node.toString()
// node如果是數字,則沒有length,就會判斷不準確,所以要把所有的值轉換為字符串
const str = node === 0 || node ? node.toString() : node
if (!str || !str.length) {
flag = false
break
}
}
}
}
recurse(arr)
return flag
}
console.log('flag', isArrayEmpty([])) // false
console.log('flag', isArrayEmpty('')) // false
console.log('flag', isArrayEmpty([null])) // false
console.log('flag', isArrayEmpty([[[[]]], 'hello', 'world'])) // false
console.log('flag', isArrayEmpty([[[['']]], 'hello', 'world'])) // false
console.log('flag', isArrayEmpty([[[['']]], [], 'world'])) // false
console.log('flag', isArrayEmpty([[[['']]], [0], 'world'])) // false
console.log('flag', isArrayEmpty([1, [[['']]], [0], 'world'])) // false
console.log('flag', isArrayEmpty([1, [1, [['']]], [0], 'world'])) // false
console.log('flag', isArrayEmpty([1, [[1, ['']]], [0], 'world'])) // false
console.log('flag', isArrayEmpty([0, [], 'world'])) // false
console.log('flag', isArrayEmpty([0, [[]], 'world'])) // false
console.log('flag', isArrayEmpty([0, [['']], 'world'])) // false
console.log('flag', isArrayEmpty([0, '', 'world'])) // false
console.log('flag', isArrayEmpty([null, 1, 'world'])) // false
console.log('flag', isArrayEmpty([0, [1, [null]], 'world'])) // false
console.log('flag', isArrayEmpty([0, undefined, 'world'])) // false
console.log('flag', isArrayEmpty([0, [undefined], 'world'])) // false
console.log('flag', isArrayEmpty([0, [[undefined]], 'world'])) // false
console.log('flag', isArrayEmpty([0, [0], 'world'])) // true
console.log('flag', isArrayEmpty([0, 0, 'world'])) // true
console.log('flag', isArrayEmpty([0, 1, 'world'])) // true
在實現的過程中,雖然也想使用 some 和 every 方法(二者的具體使用方法請自行查閲其API),但好像都不行,難道是我不會用?總之是實現了我想要的方法。如果捧場的您有什麼更好地實現方法,歡迎評論或找我交流,望不吝賜教,謝謝!