且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何处理可能未定义的数据的调用函数?

更新时间:2023-11-13 15:25:58

在使用地图之前检查数组:

Check the array before using map:

arr && arr.map()

OR,

arr && arr.length && arr.map() // if you want to map only if not empty array

OR,

我们甚至可以像这样使用(由 devserkan 评论):

We can even use like this (as commented by devserkan):

(arr || []).map()






根据您的评论:


As per your comment:


我希望有一个安全的导航操作符,比如C#(arr?.map())

I wish there was a safe navigation operator like with C# (arr?.map())

是的,很明显。这在JavaScript中称为可选链接,仍在提案中。如果它被接受,那么你可以这样使用:

Yes, obviously. This is called optional chaining in JavaScript which is still in proposal. If it is accepted, then you may use like this:

arr?.map()

您可以在中看到它您可以使用 babel预设stage1 的舞台1

You can see it in staging 1 for which you may use babel preset stage1

但显然,除了检查数组长度外,您的要求将无法满足:

But obviously, except the checking array length, your requirement will not be fulfilled:


这会导致错误,因为当然,数组的第一个索引是未定义的。

This results in an error because, of course, the first index of the array is undefined.

所以,我建议您使用:

arr && arr.length && arr.map()