Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
953 views
in Technique[技术] by (71.8m points)

How to reverse a string in JavaScript using a "for...in" loop?

I have a piece of JavaScript code using a for loop to reverse a string. However, I would like to know if it is possible to use a for in loop instead and how would I go about that?

     function reverse(str){
         var reversedString = '';
         for (var i = str.length - 1; i >= 0; i--){
            reversedString = reversedString + str[i];
     }
     return reversedString;
   }

   alert(reverse('hello'));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From MDN Docs

for...in should not be used to iterate over an Array where the index order is important.

Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order. The for...in loop statement will return all enumerable properties, including those with non–integer names and those that are inherited.

Because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index (or Array.prototype.forEach() or the for...of loop) when iterating over arrays where the order of access is important.

let iterable = '1234567';
String.prototype.hello = "hello";  // doesn't affect
let reversed = "";
for (let value of iterable) {
  reversed = value + reversed;
}

console.log(reversed);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...