How to refer to a string in an array of strings?

I have the following:

var tags = ["Favorite", "Starred", "High Rated"]; for (var tag in tags) { console.log(tag); } 

Output

 0 1 2 

I would like him to output:

 Favorite Starred High Rated 

How can I do it? Thanks.

+4
source share
2 answers

Array fix:

To create an array of strings, do not use for..in , use the vanilla for loop:

 var tags = ["Favorite", "Starred", "High Rated"]; for (var i = 0; i < tags.length; i++) { // proper way to iterate an array console.log(tags[i]); } 

Output:

 Favorite Starred High Rated 

Proper use of for..in :

It is intended for the properties of an object, for example:

 var tags2 = {"Favorite": "some", "Starred": "stuff", "High Rated": "here"}; for (var tag in tags2) { // enumerating objects properties console.log("My property: " + tag +" value is " +tags2[tag]); } 

Output:

 My property: Favorite value is some My property: Starred value is stuff My property: High Rated value is here 

Side effects of for..in with arrays:

Don't take my word for it, let's see why not use it: for..in in arrays can have side effects. Take a look:

 var tags3 = ["Favorite", "Starred", "High Rated"]; tags3.gotcha = 'GOTCHA!'; // not an item of the array // they can be set globally too, affecting all arrays without you noticing: Array.prototype.otherGotcha = "GLOBAL!"; for (var tag in tags3) { console.log("Side effect: "+ tags3[tag]); } 

Output:

 Side effect: Favorite Side effect: Starred Side effect: High Side effect: GOTCHA! Side effect: GLOBAL! 

See the demo script for these codes.

+6
source

Using in in for loops in JavaScript is not like : in Java or foreach in other languages ​​- instead of referencing an element, it provides its own index. If you use a framework like jQuery, there is a method - $.each , which gives access to an element (not just an index) through a callback when repeating:

 var a = ["Favorite", "Starred", "High Rated"]; $.each ( a, function ( index, data ) { console.log ( data ); }); 
0
source

Source: https://habr.com/ru/post/1490001/


All Articles