How to avoid 'cannot read property of undefined' errors?

前端 未结 16 2377
野性不改
野性不改 2020-11-22 06:02

In my code, I deal with an array that has some entries with many objects nested inside one another, where as some do not. It looks something like the following:



        
16条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 06:29

    You can avoid getting an error by giving a default value before getting the property

    var test = [{'a':{'b':{'c':"foo"}}}, {'a': "bar"}];
    
    for (i=0; i

    This works great with arrays too:

    const entries = [{id: 1, name: 'Scarllet'}]
    // Giving a default name when is empty
    const name = (entries.find(v => v.id === 100) || []).name || 'no-name'
    console.log(name)

提交回复
热议问题