Reputation: 6928
i want to add number of elements in a collection in javascript,as doing in following vb's code
Dim myList As New List(Of String)
Dim i As Integer
For i = 0 To rep_UnAssignComps.Items.Count
myList.Add(i)
Next
I want to compare this collection with a particular value.provide me syntax for comparing the value also. like
myList.Contains(val1)
Upvotes: 2
Views: 15253
Reputation: 49215
Not sure what you want to store in the collection but in java-script, you have two choices to achieve collections.
First is to use arrays. For example,
var arr = []; // empty array
arr.push('A');
arr.push('B');
arr.push('C');
alert(arr.length); // alerts 3
alert(arr[1]); // alerts B (zero based indexing)
To check if any element exists or not, you have to run a loop over an array comparing element at each index.
Another method will be using java-script object as hash table. Essentially, every java-script object can have multiple properties that are essentially name-value pairs. For example,
var o = { } // empty object
o["prop1"] = "A"; // Added property named prop1 with value "A"
o["prop2"] = "B"; // Added property named prop2 with value "B"
o["prop3"] = "C"; // Added property named prop2 with value "C"
alert(o["prop1"]); // alerts A
alert(o.prop2); // alerts B - notice alternate syntax
alert(o["prop4"]); // alerts undefined - because we are accessing non-existent property
if (o["prop3"]) {
alert("prop3 exists"); // to check for some property
}
for (p in o) { // iterate all properties
alert(p); // alerts property name
alert(o[p]); // alerts property value
}
Upvotes: 10
Reputation: 618
var myList = []
var i = 0;
if "rep_UnAssignComps" is an array use for loop else use for in
if (rep_UnAssignComps instanceof Array) {
for (i = 0; i < rep_UnAssignComps.length; i++){
myList.push(i);
}
}else {
for(var name in rep_UnAssignComps){
if (rep_UnAssignComps.hasOwnProperty(name)){
myList.push(i);
i++;
}
}
}
To compare use:
//Returns the first index at which a given element can be found in the array, or -1 if it is not present
myList.indexOf(val1);
Upvotes: 0
Reputation: 10604
Use push
method http://www.w3schools.com/jsref/jsref_push.asp
Upvotes: 0