在一个字符串中找到所有数字的总和,该数字可被3整除,并找到最后一个这样的数字(使用JavaScript)示例“ 8中的最佳6将获得9分”,sum = 15,last = 9。
答案 0 :(得分:2)
确定-将split
,reduce
和filter
与%
(取模)一起使用是可除的:
const str = "The best 6 of 8 will get 9 points";
const strArr = str.split("");
const threesArr = strArr.filter(e => parseInt(e) % 3 == 0);
const sumOfThrees = threesArr.reduce((acc, curr) => acc + parseInt(curr), 0);
const allNumbers = strArr.filter(e => parseInt(e));
const lastNumber = allNumbers[allNumbers.length - 1];
console.log("Sum: " + sumOfThrees);
console.log("Last: " + lastNumber);