Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
974 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 Reply

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...