Reputation: 477
I am trying to understand for loops totally. I made my research and understand a little.
I Know loops like
for(var i = 0; i < 5; i++) { console.log(i) }
Which means continue to increment i
starting from 0
as log as i
is less than 5
I also know loops like
var a = [];
a[5] = 5;
for (var x in a) {
console.log(x);
}
Which means loop for x in a and would log 5;
Was searching playing around researching and then i see something like
function aNumber() {
var aInt = 521;
var intString = aInt.toString();
var intLength = intString.length;
var result = 0;
for (var i in intString) {
result += Math.pow((+intString[i]), intLength);
}
console.log(result);
//...
}
aNumber();
I understand the conversion of int
to string
. But the loop is new to me.
I know what the Math.pow()
function does like it take to parameters (Math.pow(2,2) is same as 2**2) and the +
in +intString
passes the string
as an int
What i don't really understand is this part here
result += Math.pow((+intString[i]), intLength);
Its making the whole loop
look confusing.
Can someone help explain it for me in simple terms just like i explained the others? Thanks
Upvotes: 3
Views: 80
Reputation: 370659
for..in
loops iterate over the enumerable property names on the object (including properties inherited from the prototype). Because strings' enumerable properties are always their numeric indicies and nothing else, the line:
for (var i in intString)
can be replaced with
for (let i = 0; i < intString.length; i++)
while leaving the rest of the code the same, and it will perform identically. The intString[i]
expression just refers to the current character being iterated over.
But I wouldn't recommend using for..in
loops in most cases - it's not hard to confuse with for..of
(which is quite different), and array methods are often nicer to work with. For example, the code that generates the result
in your code can be replaced with the use of Array.prototype.reduce
, which can generate the result
at once, without any reassignment:
const intString = '521';
const intLength = intString.length;
const result = Array.prototype.reduce.call(
intString,
(a, intChar) => a + (intChar ** intLength),
0 // initial value of accumulator a
);
console.log(result);
Upvotes: 4