Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reference the string in a array of strings? [duplicate]

I have the following:

var tags = ["Favorite", "Starred", "High Rated"];

for (var tag in tags) {
    console.log(tag);
}

Output is

0
1
2

I'd like it to output:

Favorite
Starred
High Rated

How do I do this? Thanks.

like image 314
Steven Avatar asked Jul 06 '13 02:07

Steven


People also ask

How do you reference a string in an array?

You can declare a reference variable for an array of String references: String[] strArray; // 1. This declares a variable strArray which in the future may refer to an array object.

Can array have duplicate values?

Using the has() method In the above implementation, the output array can have duplicate elements if the elements have occurred more than twice in an array. To avoid this and for us to count the number of elements duplicated, we can make use of the use() method.

How do you remove duplicate values from an array of strings?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays.sort(arr) method.


1 Answers

Itearting over an array:

That's an array of strings, don't 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 usage of for..in:

It is meant for object's properties, like:

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

Output:

My property: Favorite's value is some
My property: Starred's value is stuff
My property: High Rated's 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 a demo fiddle for these codes.

like image 113
acdcjunior Avatar answered Oct 06 '22 13:10

acdcjunior