I'm refering to an entry in an array by it's string key, as in
foo["bar"]. Is there a way to get the numeric index of that array
without iterating through the entire array?
What I need to do is find the "next" or "previous" entry in the array,
but the keys are strings, instead of numerical indeces.
thanks for your help. 6 2233 ro*******@gmail .com said the following on 3/24/2006 6:14 PM: I'm refering to an entry in an array by it's string key, as in foo["bar"]. Is there a way to get the numeric index of that array without iterating through the entire array?
bar does not have a "numeric index" as it's not truly an array entry but
rather it is a property of the array.
What I need to do is find the "next" or "previous" entry in the array, but the keys are strings, instead of numerical indeces.
You could use for-in to loop through the array and build a new -
numerically indexed - array and then use a "next" and "previous" entry.
--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/ ro*******@gmail .com wrote: I'm refering to an entry in an array by it's string key, as in foo["bar"]. Is there a way to get the numeric index of that array without iterating through the entire array?
That property doesn't have an index. If you add a property to an array like:
var foo = new Array();
foo['bar'] = 'some value';
alert(foo.lengt h); // Shows '0'
you have added a property to the array object just like you have to any
other common object - arrays are objects with a special length property and
a few built-in methods, otherwise they are just objects. The only 'order'
that such properties have is the order in which they are added to the object.
The only way to read them in any sort of order is using for..in, and I
don't think that is guaranteed to return them in the order they were added
(though it may very well do so in most cases). The spec sect 12.6.4 says:
"The mechanics of enumerating properties ... is implementation
dependent. The order of enumeration is defined by the object."
Try this:
var foo = [];
foo[foo.length] = 'zero';
foo['bar'] = 'one';
foo['1'] = 'two';
foo['10'] = 'three';
foo['bob'] = 'four';
foo['5'] = 'five';
for (var p in foo){
alert(foo[p]);
}
I get: one, four, zero, two, five, three in Safari,
and: zero, one, two, three, four, five in Firefox and IE.
If you were to use for..in to find 'two', then look for the property with
the next highest index, you'd get back 'undefined'. If you keep going up
the indexes until you find one that is defined, you'll get 'five'.
The next value returned after 'two' in the for..in series is either 'five'
or 'three', depending on the browser.
What I need to do is find the "next" or "previous" entry in the array, but the keys are strings, instead of numerical indeces.
The special properties of an array are only useful if you use numeric
indexes (remembering that all property names, including numeric indexes,
are stored as strings). If you aren't using any numeric indexes, then you
should use a plain object and adding your own methods to create an order
and indexes.
--
Rob
Thanks for the very thorough response, Rob.
//Assume the associative array:
meals["fish"] = "kipper";
meals["pasta"] = "spagbol";
meals["curry"] = "tandoori";
meals["meat"] = "tartare";
// There are no indexes, there are keys.
// get an array of keys
k = new Array(0);
for(i in meals) {
k[k.length] = i;
}
k.sort(); // to sort the keys alphabetically, not required, can be
useful
// otherwise there is no contract as to whether
// the keys will be returned in insertion order or not
// You can thus get the items in defined order and via numeric index
meals[ k[x] ];
/*
Try otherwise a data type: the following can be passed an associative
array. Calling ietm( number ) gets the corresponding item. calls to
next() and prev() do what you'd expect
You could improve on this by, say, getting the internal index number to
loop, or do something appropriate on reaching start or end, check the
requested index is not out of bounds etc */
function Iterator(src_ar ray) {
this.keys = new Array(0);
this.internal = src_array;
this.i = 0;
for(var i in internal) {
keys[keys.length] = i;
}
}
function getnextitem() {return this.internal[ this.keys[i++] ];}
function getprevitem() {return this.internal[ this.keys[i--] ];}
function getitem(idx) {
this.i = idx;
return this.internal[ this.keys[idx] ];
}
function getisize(idx) {return this.internal.l ength;}
Iterator.protot ype.next = getnextitem;
Iterator.protot ype.prev = getprevitem;
Iterator.protot ype.item = getitem;
Iterator.protot ype.size = getsize;
// === example of use:
mealiterator = new Iterator(meals) ;
document.write( mealiterator.it em(2) );
document.write( mealiterator.ne xt() );
document.write( mealiterator.ne xt() );
// Good luck, and bon apétit!
//correction:
// some functions were not quite correct. below they are corrected
function Iterator(src_ar ray) {
this.keys = new Array(0);
this.internal = src_array;
this.i = 0;
for(var n in internal) {
keys[keys.length] = n;
}
}
function getnextitem() {return this.internal[ this.keys[++this.i] ];}
function getprevitem() {return this.internal[ this.keys[--this.i] ];}
/* To those who think they saw this before:
I have deleted my previous posts. this is a new post with
code that actually works (!)
The importance of testing code before publishing :-)
*/
//Assume the associative array:
meals = new Array(0);
meals["fish"] = "kipper";
meals["pasta"] = "spagbol";
meals["curry"] = "tandoori";
meals["meat"] = "tartare";
// There are no "indexes", there are "keys".
// get an array of keys:
k = new Array(0);
for(i in meals) {
k[k.length] = i;
}
k.sort(); // to sort the keys alphabetically, not required, can be
useful
// otherwise there is no contract as to whether
// the keys will be returned in insertion order or not
// You can thus get the items in defined order and via numeric index
meals[ k[3] ];
/*
Try otherwise a data type: the following can be passed an associative
array, to get a data type that holds the array and can be iterated over
with function calls, with the option of sorting the keys. Calling item(
number ) gets the corresponding item. calls to next() and prev() do
what you'd expect
On calling prev() or next() at the start or end respectively of the
array will return null and the counter will be reset to the opposite
end of the array, and return null.
(see further for example of use)
*/
function Iterator(src_ar ray,sorting) {
this.keys = new Array(0);
this.internal = src_array;
this.i = 0;
for(var n in this.internal) {
this.keys[this.keys.lengt h] = n;
}
if(sorting) {this.keys.sort ();}
}
function getnextitem() {
++this.i;
if( this.i >= this.keys.lengt h ) {this.i = -1;return null;}
return this.internal[ this.keys[this.i] ];
}
function getprevitem() {
--this.i;
if( this.i < 0 ) {this.i = this.keys.lengt h;return null;}
return this.internal[ this.keys[this.i] ];
}
function getitem(idx) {
if( idx >= this.keys.lengt h || idx < 0 ) {return null;}
this.i = idx;
return this.internal[ this.keys[idx] ];
}
function getsize() {return this.keys.lengt h;}
Iterator.protot ype.next = getnextitem;
Iterator.protot ype.prev = getprevitem;
Iterator.protot ype.item = getitem;
Iterator.protot ype.size = getsize;
// === example of use:
mealiterator = new Iterator(meals, true);
document.write( mealiterator.it em(2)+", " );// tartare
document.write( mealiterator.ne xt()+", " );// spagbol
document.write( mealiterator.ne xt()+", " );// null
document.write( mealiterator.ne xt()+"<br>" );// tandoori (we are back at
the start)
document.write( mealiterator.it em(1)+", " );// kipper
document.write( mealiterator.pr ev()+", " );// tandoori
document.write( mealiterator.pr ev()+", " );// null
document.write( mealiterator.pr ev()+"<br>" );// spagbol - back at end This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: jerrygarciuh |
last post by:
Hello,
In reading through the list of array-related functions I did not find on
which returns the numeric index where the array's internal pointer currently
sits. Is there such a function?
TIA
jg
|
by: Gustaf Liljegren |
last post by:
Hi,
I've been struggling with this for days now. Hope to get some help here,
but some knowlegde in XML is required. I'm trying to create a back-of-
book index in XML, following this DTD:
<!ELEMENT index (entry | group)*>
<!ELEMENT entry (text, pages)>
<!ELEMENT text (#PCDATA)>
<!ELEMENT pages (#PCDATA)>
|
by: Stefan Mueller |
last post by:
I choose 'Entry 4' and click then on the button 'Set' to set the index to
'Entry 2'. If you press now the cursor down key 'Entry 5' instead of 'Entry
3' shows up with Mozilla Firefox. With Internet Explorer and Opera it works
fine; 'Entry 3' shows up.
Is this a bug within Mozilla Firefox or do I have any possibility to change
this wrong...
|
by: Fir5tSight |
last post by:
Hi,
I declare PageObjectsArray1 and PageObjectsArray2 as ArrayList. Each
element in the array is a Page object. Now I want to compare every pair
of Page objects of the same index in the two arrays.
However, it seems that there is no method in ArrayList such as
"GetAt(i)" so that I can return a Page object at a particular location
in the...
|
by: Joe Rattz |
last post by:
Ok, I can't believe what I am seeing. I am sure I do this other places with
no problems, but I sure can't here.
I have some code that is indexing into the ItemArray in a DataSet's DataRow.
I basically want to change the value of the data stored at a particular
index in the ItemArray. Ideally, I would like for my code to look like this...
| |
by: d d |
last post by:
I have an array of objects that start out looking like this:
var ra=;
I want to be able to access the array by index number from some code,
and by the name property from other code, as if it had been defined like
this instead:
var ra=;
ra = {name:"fred",someproperty:"hello fred"};
|
by: anuptosh |
last post by:
Hi,
I have been trying to run the below example to get a Oracle Array as an output from a Java code. This is an example I have found on the web. But, the expected result is that the code should return me Array element type code 1, but it is returning me type code 12 and the array in a junk or unreadable format . Our environment is JDK 1.4,...
|
by: student4lifer |
last post by:
If I have a multidimentional array that contains many arrays inside as
follows:
$voters=array(array('name'=>'Joe', 'profession'=>'blumbing',
'state'=>'Ohio'),
array('name'=>'Obama', 'profession'=>'senator', 'state'=>'Ilinois'),
array('name'=>'Palin', 'profession'=>'moose hunter',
'state'=>'Alaska'),
..
..
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it. ...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
| |
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...
| |