網站搜尋

javascript - 如何在 TypeScript 陣列中找到第一個非 null 值?


我有一個 arr 變數,看起來如下:

const arr = [undefined, undefined, 'hello', 'hello', 'hi'];

我想列印出 arr 陣列變數中第一個 non-null 值。

在上述陣列中,輸出應該是 hello

我已經寫了以下的邏輯,但它沒有給出正確的結果:

const arr = [undefined, undefined, 'hello', 'hello', 'hi'];
const index = arr.length;

while (index-- && !arr[index]);

console.log(arr[index]);

答案#1

只需使用 find:

const arr = [undefined, undefined, 'hello', 'hello', 'hi'];

console.log(arr.find(el => el !== undefined))

它返回提供的陣列中第一個符合提供的測試函數的元素的值。

答案#2

const arr = [undefined, null, 'hello', 'hello', 'hi'];

console.log(arr.find(el => el))
// or
console.log(arr.find(el => !!el))