简体   繁体   English

如何为数组中的第一个元素返回属性值,如果没有元素则返回0?

[英]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: 在我的HTML中,我有以下代码块:

<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 . word对象可以具有0个或多个wordForms ,每个wordForm都有一个属性wordFormIdentityId

In javascript how can I get the wordFormIdentityId of the first wordForm or return 0 if there are no wordForms. 在JavaScript我如何能得到wordFormIdentityId第一wordForm或返回0,如果没有词形等。 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. 我也以Typescript回应。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何返回第一个字母为大写字母的数组的所有元素 - how can I return all the elements of an array with the first letter as a capital letter 如何检查具有可变子元素的元素是否包含具有特定值的数组属性? - How can I check if an element with a changeable child element contains an array property with a certain value? 如何在第一个值上对数组排序? - How can I sort an array on the first value? 如何检查具有可变子元素的元素是否包含具有特定值的数组属性? - How can I check if an element with a changeable child contains an array property with a certain value? 如何在数组中找到2个元素并以PHP形式返回数组? - How can I find 2 elements in an array and return the array in a form in PHP? 如何返回属性与数组匹配的对象数组? - How can I return an array of objects whose property matches an array? 我怎样才能 map 并返回反应中的第一个和最后一个元素? - How can I map and return first and last element in react? 如何返回数组的计算值? - How can I return the calculated value of an array? 如何使用对象更改数组中每个属性的值并返回它? - How do i change the value of each property in an array with objects and return it? 如何从元素数组中动态获取元素的值? - How do I dynamically get the value of an element from an array of elements?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM