简体   繁体   中英

How can I return a property value for the first element in an array or 0 if there are no elements?

In my HTML I have this code block:

<div ng-click="wos.wordWordFormRowClicked(wf)"
         ng-repeat="wf in word.wordForms">
   ...
</div>

The word object can have 0 or many wordForms and each wordForm has a property wordFormIdentityId .

In javascript how can I get the wordFormIdentityId of the first wordForm or return 0 if there are no wordForms. Hope this makes sense, if not please ask and I will try to explain more.

Here are the typescript interfaces:

interface IWord {
    wordForms: IWordForm[];
    wordId: string;
}

interface IWordForm {
    definition: string;
    wordFormId: string;
    wordFormIdentity: number;
    wordId: string;
}

Am I missing something or does this handle it? I responded in Typescript as well.

function getFirstId (word:IWord) :number {
    if(word && word.wordForms && word.wordForms.length > 0) {
        return word.wordForms[0].wordFormIdentity;
    }
    return 0;
}

I think that's what you need in your function:

if(word.wordForms)
   return word.wordForms[0].wordFormIdentity || 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM