我真的很困惑如何解决这个问题:
我有一个像这样的数组:
arr=["X12","Z1","Y7","Z22","X4","X8"]
我希望对以下元素执行数学功能:
每个以“ X”开头的元素将具有固定值5
,因此,如果数组3
中有arr
个以“ X”开头的元素,则应为: (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.
}
});
}
什么是无杂乱的方式做到这一点的?
答案 0 :(得分:3)
您可以尝试将数组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);
答案 1 :(得分:1)
您也可以尝试
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)