Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

javascript - How to find first non null value in a typescript array?

I have an arr variable which looks as below:

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

I want to print out the first non-null value from within the arr array variable.

In above array, the output should be hello

I have written following logic but it is not giving the correct result:

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

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

console.log(arr[index]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just use find:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...