假设我们有一个这样的数字数组-
const arr = [1, 5, 2, 1, 2, 3, 4, 5, 7, 8, 7, 1];
我们需要编写一个JavaScript函数,该函数接受一个这样的数组并计算数组中所有不同元素的总和。
例如:
上面提到的数组的输出将是-
30
为此的代码将是-
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