how can I get the indentifier of an associative array (not Array object) in a for loop?
like so:
var i = 0;
for(i=0;i<=myArray;i++)
{
if(myArray.ident == 'title') alert('The title is ' + myArray['title'开发者_JS百科]);
}
You can do it using a different for()
loop, like this:
var myArray = { title: "my title", description: "my description" };
var i = 0;
for(var i in myArray) {
//if(i == 'title') is the check here...
alert('The '+ i + ' is ' + myArray[i]);
}
Inside the loop, i
is your identifier, e.g. title
and description
. You can play with this example here
var i;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (i = 0; i < mycars.length; i++) {
document.write(mycars[i] + "<br>");
}
ident is the identifier in your case and 'title'
is its value ..
Please show us the actual array ..
normally to loop through an associative array you would do it like this..
for (key in myArray)
{
if (key == 'title')
alert('The title is ' + myArray[key]);
}
Depends somewhat on how you construct myArray
, in general:
var myArray = {
title: "foo",
bleep: "bloop"
}
for (var k in myArray) {
if (k == "title")
alert('The title is ' + myArray[k]);
}
As @Nick Craver posted, loop through your data object (associative array), preferrably using the compact syntax, and check whether the property matches your string:
var myData = { /* properties: values */ } ;
var string = /* string to match */ ;
for(var n in myData) {
if(n == string) {
// do something
}
}
精彩评论