简体   繁体   中英

Angular 4 - Sum of Array

new to ng4/typescript and having some difficulty. How do I sum the items in an array?

Added在此处输入图片说明 screenshot of what it looks like in action for example

        for (let card of this.cards) {
              for (let val of card.cards){
                if(val.value == "JACK"){
                  val.value = 10;
                }
                if (val.value == "QUEEN"){
                  val.value = 10;
                }
                if (val.value == "KING"){
                  val.value = 10;
                }
                if (val.value == "ACE"){
                  val.value = 10;
                }

                this.hand = Number(val.value) + Number(val.value); (I'm sure this is wrong)

             }
          }

Use Array#Reduce :

 // Array of numbers var array = [1,2,3,4,5]; var sum = array.reduce((acc, cur) => acc + cur, 0); console.log(sum) // Array of strings var toNumber = ['1','2','3','4','5']; var sumNumber = toNumber.reduce((acc, cur) => acc + Number(cur), 0) console.log(sumNumber);

let sum = array.reduce(function (acc, cur) { return acc + cur; });

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