【问题标题】:Math with typescript array - Angular带有打字稿数组的数学 - Angular
【发布时间】:2023-03-09 11:21:01
【问题描述】:

我真的很困惑如何解决这个问题:

我有一个这样的数组:

arr=["X12","Z1","Y7","Z22","X4","X8"]

我希望对元素执行数学函数,例如:

每个以“X”开头的元素都有一个固定值5,因此如果数组arr中有以“X”开头的3元素,它应该是:(fixed value of X) multiplied by (No. of "X" element occurrences inside array) = 5x3 = 15.

我尝试了类似的方法来计算编号。 “X”元素的出现次数,但它不起作用。

var xcounter = 0;
calculate(){
          this.arr.forEach(element => {
            if(this.arr.includes("X"))
            {
              this.xcounter++; //this doesn't give me no. of X element occurrences though.
            }
          });
        }

什么是一种简洁的方式来做到这一点?

【问题讨论】:

    标签: arrays angular typescript


    【解决方案1】:

    您可以尝试使用数组filter() 和字符串startsWith() 方法。

    var arr = ["X12","Z1","Y7","Z22","X4","X8"];
    var valueX = 5;
    
    var occurencesX = arr.filter(item => item.startsWith('X')).length;
    
    console.log(occurencesX * valueX);

    【讨论】:

      【解决方案2】:

      你也可以试试这个

      1. 循环进入你的数组
      2. 找出有多少次你找到了开头有 X 的值

      var  arr=["X12","Z1","Y7","Z22","X4","X8"]
      let total = 0
      arr.forEach(
        (row) =>{
              total =  row.startsWith('X')? total + 1 : total
        }
      )
      
      console.log(total * 5)

      【讨论】:

        猜你喜欢
        • 2021-03-29
        • 2017-08-17
        • 2016-07-22
        • 2018-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-28
        • 1970-01-01
        相关资源
        最近更新 更多