我有一个arr
变量,如下所示:
const arr = [undefined, undefined, 'hello', 'hello', 'hi'];
我想non-null
从arr
数组变量中打印出第一个值。
在上面的数组中,输出应为 hello
我写了以下逻辑,但是没有给出正确的结果:
const arr = [undefined, undefined, 'hello', 'hello', 'hi'];
const index = arr.length;
while (index-- && !arr[index]);
console.log(arr[index]);
只需使用find
:
const arr = [undefined, undefined, 'hello', 'hello', 'hi'];
console.log(arr.find(el => el !== undefined))
它返回提供的数组中满足提供的测试功能的第一个元素的值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句