function specialMix(...data) {
// Your Code Here
let result = 0;
for (let i = 0; i < data.length; i++) {
if (typeof data[i] === "number") {
result += data[i];
}
}
return result;
}
调用函数
console.log(specialMix(10, 20, 30)); // 60
console.log(specialMix("10Test", "Testing", "20Cool")); // 30
console.log(specialMix("Testing", "10Testing", "40Cool")); // 50
console.log(specialMix("Test", "Cool", "Test")); // All Is Strings.
这里最简单的方法是使用正则表达式替换:
function specialMix(...data) {
data = data.map(x => x.replace(/D+/g, ""));
return data.reduce((p, a) => a ? p + parseInt(a) : p, 0);
}
console.log(specialMix("10Test", "Testing", "20Cool")); // 30
console.log(specialMix("Testing", "10Testing", "40Cool")); // 50
console.log(specialMix("Test", "Cool", "Test")); // All Is Strings.
使用regex将是最短的方法。
还有一个不使用regex的解决方案,您可以将其用于参考
步骤:
- 排除每个元素中的非数字字符
- 排除空字符串
- 将数字字符串强制转换为数字
- 计算总和
function excludeString(el) {
return String(el)
.split("")
.filter(char => Number.isInteger(+char))
.join("")
}
function specialMix(...data) {
return data
.map(excludeString)
.filter(Boolean)
.map(Number)
.reduce((sum, el) => sum + el, 0)
}
console.log(specialMix(10, 20, 30)) // 60
console.log(specialMix("10Test", "Testing", "20Cool")) // 30
console.log(specialMix("Testing", "10Testing", "40Cool")) // 50
console.log(specialMix("Test", "Cool", "Test")) // All Is Strings.