簡體   English   中英

有人能告訴我如何只對嵌套在我的 JavaScript 數組中的一些項目求和嗎?

[英]Can someone tell me how to sum only some of items nested in my JavaScript array?

我對這個代碼不是很自豪ㅠㅠ 我在數組中有 6000 個對象,並且只想對數組中的 10 個項目求和。 現在我將十個編碼塊放入程序中。

有人可以告訴我如何使它看起來像編程嗎?

<Text style={styles.text}>[{Number((items.find( x => x.id === indexTwoId+101).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+102).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+103).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+104).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+105).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+106).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+107).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+108).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+109).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+110).as==='1'?'1':'0'))}/10]</Text>

我的數組如下;

    count: 1,
    categories: [
        {id:1,as:0},
        {id:2,as:0},
        {id:3,as:0},
        {id:4,as:0},
        {id:5,as:0},
        {id:6,as:0},
        {id:7,as:0},
        {id:8,as:0},
        {id:9,as:0},
        {id:10,as:0},
.
.
.
.]}```

我沒有使用 React 的經驗,但在“常規”JS 中你可能會做這樣的事情:

let sum = items.reduce((item, total) => {
    if (item.id < indexTwoId + 101 || item.id > indexTwoId + 110) return total;
    if (item.as === '1') return total + 1;
    return total;
}, 0)

您可能可以使用三元運算符將其“翻譯”為一行。

編輯:如果您只想按標准計算項目,則:

items.filter(x => x.id >= indexTwoId + 101 && x.id <= indexTwoId + 110 && x.as === '1').length

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM