[英]How to continuously add to a variable on iteration of a for-loop, with jQuery?
[英]How to add to a variable when addition is in an for-loop
这是来自codewars的问题。 继承人我的代码。
function narcissistic(value) {
var total = 0
var valLength = value.length
const digit = [...`${value}`];
for(var i = 0; i < value.length; i++){
total += Math.pow(value.length , digit)
}
if(total == value){ return true
} else {
return false
}
}
我遇到的问题是我不知道为什么当我做total += value.length * digit[i]
它没有添加到total
。 有任何想法吗?
您可以尝试这样的操作:您需要将函数参数转换为具有不同值的数组,然后计算每个数字的幂,然后添加到总数中。 此外,尝试使用 let 而不是 var,因为它更适合块级作用域。
function narcissistic(value) { let total = 0; const digit = [...`${value}`]; for (let i = 0; i < digit.length; i++) { total += Math.pow(digit[i], digit.length); } if(total === value) { return true; } else { return false; } } console.log(narcissistic(153)); console.log(narcissistic(432));
这个函数可以返回你需要的值
function narcissistic(value) {
const stringValue = [...`${value}`];
const len = stringValue.length;
const sum = stringValue.reduce((prev, current) => {
return prev + Math.pow(parseInt(current, 10), len);
}, 0)
return `${value}` === sum.toString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.