如何在打字稿数组中找到第一个非空值?
我有一个arr如下所示的变量:
const arr = [undefined, undefined, 'hello', 'hello', 'hi'];
const arr = [undefined, undefined, 'hello', 'hello', 'hi'];
我想打印出数组变量中的第一个non-null值arr。
在上面的数组中,输出应该是 hello
我写了以下逻辑,但没有给出正确的结果:
回答
只需使用find:
const arr = [undefined, undefined, 'hello', 'hello', 'hi'];
console.log(arr.find(el => el !== undefined))
它返回提供的数组中满足提供的测试函数的第一个元素的值。