我们需要编写一个JavaScript函数,该函数接受一个这样的数组并计算数组中所有不同元素的总和。
例如:假设我们有一个数字数组,如下所示:
const arr = [1, 5, 2, 1, 2, 3, 4, 5, 7, 8, 7, 1];
上面提到的数组的输出为20。
以下是代码-
const arr = [1, 5, 2, 1, 2, 3, 4, 5, 7, 8, 7, 1];
const distinctSum = arr => {
let res = 0;
for(let i = 0; i < arr.length; i++){
if(i === arr.lastIndexOf(arr[i])){
res += arr[i];
};
continue;
};
return res;
};
console.log(distinctSum(arr));输出结果
以下是控制台中的输出-
30