![](/img/trans.png)
[英]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.