寫一個(gè)求和的函數(shù)sum梯找,達(dá)到下面的效果:
// Should equal 15
sum(1, 2, 3, 4, 5);
// Should equal 0
sum(5, null, -5);
// Should equal 10
sum('1.0', false, 1, true, 1, 'A', 1, 'B', 1, 'C', 1, 'D', 1,
'E', 1, 'F', 1, 'G', 1);
// Should equal 0.3, not 0.30000000000000004
sum(0.1, 0.2);
function sum() {
let args = Array.prototype.slice.call(arguments)
let sum = 0
let max = 0
let numberArr = []
args.forEach(function (item) {
let number
let match = false
let length = 0
//將字符串或者數(shù)字轉(zhuǎn)換成Number對(duì)象甲雅,true,false,null要單獨(dú)考慮
// 因?yàn)镹umber(true) === 1闸衫,Number(false||null) === 0
if (item === true || item === false || item === null) {
number = NaN
}
else {
number = Number(item)
}
if (!isNaN(number)) {
numberArr.push(number)
match = /[0-9]+\.([0-9]+)/.exec(number.toString())
if (match) {
length = match[1].length
}
if (length > max) {
max = length
}
}
})
numberArr.forEach(function (item) {
sum = sum + item * Math.pow(10, max)
})
sum = sum / Math.pow(10, max)
return sum
}