Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Elementos de un array

0 views
Skip to first unread message

LuisDavid

unread,
Sep 23, 2008, 12:19:51 PM9/23/08
to
Hola grupo que tal, tengo una inquietud no se si sea sencillo, o me
estoy confundiendo; la cuestion es esta:
tengo este array.
var lista = new Array("uno","dos",tres","cuatro");
ahora como hago para que en una variable me tome un elemento del array
lista; dependiendo de la longitud del elemento; en este caso que me
extraiga el elemento: lista[3] por ser:
lista[3].length = 6 //el numero de mayor longitud respecto a los otros
elementos del array lista; ahora los elementos del array lista estan
"aleatoriamente"; no necesariamente tienen que estar en orden, y la
longitud del array puede ser distinto:
en este caso es lista.length = 4; //este valor puede variar.
"en pocas palabras quiero tomar el elemento de la lista de mayor
longitud";
es posible hacer eso o esque le pido mucho al new Array?, le agradesco
me puedan ayudar. gracias grupo. que tengan buen dia.

SAM

unread,
Sep 23, 2008, 1:11:53 PM9/23/08
to
LuisDavid a écrit :


On n'a rien compris à ces histoires de longitudes !

Puedes muy bien escoger(clasificar) tu tablero (array) sin crear un nuevo :
lista = lista.sort();
ò tanbien directamente :
lista.sort();


var lista = [ 1, 3, 5, 4, 2];
alert('lista original : ' + lista);
alert('el mayor = '+ lista.sort()[lista.length-1]);
alert('lista modificada : ' + lista);


--
sm

Thomas 'PointedEars' Lahn

unread,
Sep 23, 2008, 2:01:00 PM9/23/08
to
LuisDavid wrote:

> tengo este array.
> var lista = new Array("uno","dos",tres","cuatro");

var lista = ["uno", "dos", tres", "cuatro"];

is also possible. See <http://PointedEars.de/es-matrix>.

> ahora como hago para que en una variable me tome un elemento del array
> lista; dependiendo de la longitud del elemento; en este caso que me
> extraiga el elemento: lista[3] por ser:

lista.splice(3, 1);

<http://groups.google.com/groups?as_q=remove+element+array&as_ugroup=comp.lang.javascript&scoring=d&filter=0>

> lista[3].length = 6

You would try to assign 6 to the `length' property of the String object that
represents lista[3] ("cuatro"). Since this property is read-only, it will
not work.

> [...]


> en este caso es lista.length = 4; //este valor puede variar.

That would delete lista[4], lista[5], and so on.


HTH

PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm>

SAM

unread,
Sep 23, 2008, 7:48:59 PM9/23/08
to
LuisDavid a écrit :

> "en pocas palabras quiero tomar el elemento de la lista de mayor
> longitud";

var lista = ["uno","dos","tres","cuatro",'cinco','seis'];
var k = '';
for(i in lista) if(lista[i].length>k.length) k = lista[i];
alert('El elemento más largo es : '+k);

--
sm

LuisDavid

unread,
Sep 25, 2008, 11:51:48 AM9/25/08
to
On 24 sep, 03:48, SAM <stephanemoriaux.NoAd...@wanadoo.fr.invalid>
wrote:

SAM mira el codigo funciona es justo lo que queria pero sere un poco
mas especifico mira el array lista no se escribe textualmente como
esta; sino que es generado por el metodo match que extrae elementos de
una cadena:

<script>
var cadena = "elemtos(uno), documentos(tres), portales(cinco),
ejecutables(tres)"
var lista = cadena.match(/(\w*)/g);
//var lista = ["uno","tres","cinco","tres"];


var k = '';
for(i in lista) if(lista[i].length>k.length) k = lista[i];
alert('El elemento más largo es : '+k);

</script>

En FireFox, Netscape, Opera, Safari. k almacena esto:
El elemento mas largo es: cinco// esta OK.

Pero en IE k almacena esto:
El elemento mas largo es: elemtos(uno), documentos(tres),
portales(cinco), ejecutables(tres)

IE el metodo match si lo reconoce como array (al vizualizarlo) pero al
pasar el codigo no!!;
IE es el monton por eso quiero que funcione tambien ahi.
Sin embargo los otros navegadores si: me podes ayudar porfavor,
"la idea es que quiero extraer el contenido del parentesis mas largo
de la variable cadena" o hay otra forma de hacerlo?,

var cadena es generada por un codigo mas atras, que puede variar de 1
parentesis() a 9 parentesis() en contenidos, (varia tambien la
longitud del array), en este caso yo quiero extraer el contenido mas
largo del parentesis.
Pero IE creo que le asusta el metodo match. solo lo hace si lo paso
como array textual asi:

var lista = ["uno","tres","cinco","tres"];

. porque??? ayuda porfavor. gracias de antemano Grupo.

Jorge

unread,
Sep 25, 2008, 1:14:10 PM9/25/08
to
On Sep 24, 1:48 am, SAM <stephanemoriaux.NoAd...@wanadoo.fr.invalid>
wrote:
>
> for(i in lista) { }

Hmm, what a lovely 'for..in' !
I had never applied it to an array.

javascript:a=['0',,,,,,,,'8'], a[4]= '4', n= 0;for (i in a) { n++;
alert(i+a[i]); };alert(n+' !== '+a.length);

Is it predictable in this case ? the order of 'i', I mean ?
--
Jorge.

Jorge

unread,
Sep 25, 2008, 1:25:27 PM9/25/08
to
On Sep 25, 5:51 pm, LuisDavid <luisdavi...@gmail.com> wrote:

>
> IE el metodo match si lo reconoce como array (al vizualizarlo) pero al
> pasar el codigo no!!;
> IE es el monton por eso quiero que funcione tambien ahi.
> Sin embargo los otros navegadores si: me podes ayudar porfavor,
> "la idea es que quiero extraer el contenido del parentesis mas largo
> de la variable cadena" o hay otra forma de hacerlo?,
>

Quieres decir que en IE falla el .match() y la expresión regular ?
En qué versión(es) de IE ?
Puedes poner una muestra de cadena (la más complicada si puede ser, de
esas que dices con muchos niveles de paréntesis) a la que aplicas la
expresión regular con el .match() y falla ?

Yo aquí partiéndome los cuernos en guiri, y llegas tu y venga que
ancha es Castilla, vamos qué jeta no ?

Suerte,
--
Jorge.

SAM

unread,
Sep 26, 2008, 8:38:39 AM9/26/08
to
Le 9/25/08 7:14 PM, Jorge a écrit :

What do you mean by 'predictable' ?

javascript:a=['0',,,,,,,,'8'], a[4]= '4';for(i in a)
if(a[i])alert('elem.t #'+i+' = '+a[i]);

The order of 'i' is always from 0 to n-1

javascript:a=['0',,,,,,,,'8'], a[4]= '4', n= 0;a.sort();for (i in a) {
n++;alert('elem.t #'+i+' = '+a[i]); };alert('n = '+n+'\na.length =
'+a.length+'\nis n = a.length ? '+(n == a.length));

javascript:a=['0',,,,,,,,'8'], a[4]= '4', n= 0;a.sort();a.length=10;for
(i in a) { n++;alert('elem.t #'+i+' = '+a[i]); };alert('n =
'+n+'\na.length = '+a.length+'\nis n = a.length ? '+(n == a.length));

javascript:a=['0',,,,,,,,'8'], a[4]= '4', n= 0;a.sort();a.push(29);for
(i in a) { n++;alert('elem.t #'+i+' = '+a[i]); };alert('n =
'+n+'\na.length = '+a.length+'\nis n = a.length ? '+(n == a.length));

--
sm

SAM

unread,
Sep 26, 2008, 9:48:31 AM9/26/08
to
Le 9/25/08 5:51 PM, LuisDavid a écrit :

> On 24 sep, 03:48, SAM <stephanemoriaux.NoAd...@wanadoo.fr.invalid>
> wrote:
>> var lista = ["uno","dos","tres","cuatro",'cinco','seis'];
>> var k = '';
>> for(i in lista) if(lista[i].length>k.length) k = lista[i];
>> alert('El elemento más largo es : '+k);
>
> SAM mira el codigo funciona es justo lo que queria pero sere un poco
> mas especifico mira el array lista no se escribe textualmente como
> esta; sino que es generado por el metodo match que extrae elementos de
> una cadena:
>
> <script>
> var cadena = "elemtos(uno), documentos(tres), portales(cinco),
> ejecutables(tres)"
> var lista = cadena.match(/(\w*)/g);

\w Matches any alphanumeric character from the basic Latin alphabet,
including the underscore. Equivalent to [A-Za-z0-9_].
* Matches the preceding item 0 or more times

That will match all suites of alphanumeric characters.

Esto va a sacar todos los séquitos de carácteres alfanuméricos (incluido
los vacías)

Try (in location bar of your browser(s) ) :

javascript:var cadena = "elemtos(uno), documentos(tres),
portales(cinco),ejecutables(tres)";var lista =
cadena.match(/(\w*)/g);alert(lista);

Result :
elemtos,,uno,,,,documentos,,tres,,,,portales,,cinco,,,ejecutables,,tres,,

Si lo que quieres haber esta : '(uno),(tres),(cinco),(tres)'
hay de far : cadena.match(/\(\w*\)/g);


javascript:var cadena = "elemtos(uno), documentos(tres),
portales(cinco),ejecutables(tres)";var lista =
cadena.match(/\(\w*\)/g);var k='';for(i in lista)
if(lista[i].length>k.length)k=lista[i];alert(k);

would have to work fine with other browsers than IE

With IE (por IE) :

javascript:var cadena = "elemtos(uno), documentos(tres),
portales(cinco),ejecutables(tres)";var lista =
cadena.match(/\(\w*\)/g);alert('lista = '+lista);var
k='';for(i=0,n=lista.length;i<n;i++){alert('lista['+i+'] = '+lista[i]);
if(lista[i].length>k.length)k=lista[i];}alert('mas largo = '+k);


> //var lista = ["uno","tres","cinco","tres"];
> var k = '';
> for(i in lista) if(lista[i].length>k.length) k = lista[i];
> alert('El elemento más largo es : '+k);
> </script>
>
> En FireFox, Netscape, Opera, Safari. k almacena esto:
> El elemento mas largo es: cinco// esta OK.

No, con el mio Firefox ho : 'ejecutables'


javascript:var cadena = "elemtos(uno), documentos(tres),
portales(cinco),ejecutables(tres)";var lista =
cadena.match(/\(\w*\)/g);var k='';for(i in lista)
if(lista[i].length>k.length)k=lista[i];alert(k);

would have to work fine with other browsers than IE

With IE (por IE) :

javascript:var cadena = "elemtos(uno), documentos(tres),
portales(cinco),ejecutables(tres)";var lista =
cadena.match(/\(\w*\)/g);alert('lista = '+lista);var
k='';for(i=0,n=lista.length;i<n;i++){alert('lista['+i+'] = '+lista[i]);
if(lista[i].length>k.length)k=lista[i];}alert('mas largo = '+k);

> Pero en IE k almacena esto:
> El elemento mas largo es: elemtos(uno), documentos(tres),
> portales(cinco), ejecutables(tres)

(snip)


> . porque??? ayuda porfavor. gracias de antemano Grupo.

Porque quando hace 'for(i in lista)'
IE añade 'input' en primero index
e otros indexes que no sè los que estan.

test :

javascript:var cadena = "elemtos(uno), documentos(tres),
portales(cinco),ejecutables(tres)";var lista =
cadena.match(/\(\w*\)/g);for(in in lista)alert('index =
'+i+'\nlista['+i+'] = '+lista[i]);


so, I think you must do : for(i=0, n=lista.length; i<n; i++)

<script>
var cadena = "elemtos(uno), documentos(tres), portales(cinco),
ejecutables(tres)"
var lista = cadena.match(/(\w*)/g);
//var lista = ["uno","tres","cinco","tres"];
var k = '';

for(i=0, n=lista.length; i<n; i++)


if(lista[i].length>k.length) k = lista[i];
alert('El elemento más largo es : '+k);
</script>

Lo que sigue, utilizando 'for(i in lista)', funciona también con IE :

javascript:var cadena = "elemtos(uno), documentos(tres),
portales(cinco),ejecutables(tres)"; var
lista=cadena.match(/\(\w*\)/g).toString().split(','); var k=''; for(i in
lista) if(lista[i].length>k.length)k=lista[i];alert(k);

lista = lista.toString().split(',');

forces to set 'lista' to an array

--
sm

Thomas 'PointedEars' Lahn

unread,
Sep 26, 2008, 1:53:40 PM9/26/08
to
Jorge wrote:

> SAM wrote:
>> for(i in lista) { }
>
> Hmm, what a lovely 'for..in' !
> I had never applied it to an array.
>
> javascript:a=['0',,,,,,,,'8'], a[4]= '4', n= 0;for (i in a) { n++;
> alert(i+a[i]); };alert(n+' !== '+a.length);
>
> Is it predictable in this case ? the order of 'i', I mean ?

No; read ES3F, 12.6.4.


PointedEars
--
var bugRiddenCrashPronePieceOfJunk = (
navigator.userAgent.indexOf('MSIE 5') != -1
&& navigator.userAgent.indexOf('Mac') != -1
) // Plone, register_function.js:16

Jorge

unread,
Sep 26, 2008, 7:56:58 PM9/26/08
to
On Sep 26, 7:53 pm, Thomas 'PointedEars' Lahn <PointedE...@web.de>
wrote:

> Jorge wrote:
> > SAM wrote:
> >> for(i in lista) { }
>
> > Hmm, what a lovely 'for..in' !
> > I had never applied it to an array.
>
> > javascript:a=['0',,,,,,,,'8'], a[4]= '4', n= 0;for (i in a) { n++;
> > alert(i+a[i]); };alert(n+' !== '+a.length);
>
> > Is it predictable in this case ? the order of 'i', I mean ?
>
> No; read ES3F, 12.6.4.
>

That's what I thought, but as SAM said, however hard I try, it always
shows them in the right order.

--
Jorge.

Jorge

unread,
Sep 26, 2008, 8:03:34 PM9/26/08
to
On Sep 26, 2:38 pm, SAM <stephanemoriaux.NoAd...@wanadoo.fr.invalid>
wrote:

> Le 9/25/08 7:14 PM, Jorge a écrit :
>
> > On Sep 24, 1:48 am, SAM <stephanemoriaux.NoAd...@wanadoo.fr.invalid>
> > wrote:
> >> for(i in lista) { }
>
> > Hmm, what a lovely 'for..in' !
> > I had never applied it to an array.
>
> > javascript:a=['0',,,,,,,,'8'], a[4]= '4', n= 0;for (i in a) { n++;
> > alert(i+a[i]); };alert(n+' !== '+a.length);
>
> > Is it predictable in this case ? the order of 'i', I mean ?
>
> What do you mean by 'predictable' ?
>

That the sequence grows orderly. But the spec states that properties
might show up in any order. (See Thomas' ('Mr. spec') post...)

--
Jorge.

Conrad Lender

unread,
Sep 26, 2008, 8:26:41 PM9/26/08
to
On 2008-09-27 01:56, Jorge wrote:
> On Sep 26, 7:53 pm, Thomas 'PointedEars' Lahn <PointedE...@web.de>
..

>> > javascript:a=['0',,,,,,,,'8'], a[4]= '4', n= 0;for (i in a) { n++;
>> > alert(i+a[i]); };alert(n+' !== '+a.length);
>>
>> > Is it predictable in this case ? the order of 'i', I mean ?
>>
>> No; read ES3F, 12.6.4.
>>
>
> That's what I thought, but as SAM said, however hard I try, it always
> shows them in the right order.

For one thing, there's this possibility:

var a = ['0', '1'];
a.blah = "ho hum";
a.push('2', '3');
for (var i in a) {
document.write(i + ": " + a[i] + "<br>");
}

Now I'm afraid I'll have to partly contradict what I wrote earlier in a
different thread (alert vs. window.alert). In this specific case, I
would *not* trust implementations to always return the results in the
expected order, even though empirical evidence suggests that they
currently do. The reason why I'm more reluctant here is that we're
always warned (and that goes for various different programming
languages) that hashes / associative arrays / objects should not be
trusted to return their keys in any particular order when you iterate
like that. This is a very common pitfall in many languages. Some do have
ordered hashes (like the [weird] PHP arrays, which are actually a mix of
arrays and hashes, or Perl's pseudohashes), but I'll bet my hat that
Thomas can come up with a passage in the ECMAScript specs that says that
object properties aren't guaranteed to be returned in any particular
order in a for..in loop.

In short, it may work. I can even imagine that the current script
engines are designed to work that way, because too many badly written
scripts would fail otherwise. But I wouldn't trust it. Iterate over an
array like an array, and an object like an object.


- Conrad

Jorge

unread,
Sep 26, 2008, 8:34:13 PM9/26/08
to
On Sep 26, 2:38 pm, SAM <stephanemoriaux.NoAd...@wanadoo.fr.invalid>
wrote:
> Le 9/25/08 7:14 PM, Jorge a écrit :
>
> > On Sep 24, 1:48 am, SAM <stephanemoriaux.NoAd...@wanadoo.fr.invalid>
> > wrote:
> >> for(i in lista) { }
>
> > Hmm, what a lovely 'for..in' !
> > I had never applied it to an array.
>
> > javascript:a=['0',,,,,,,,'8'], a[4]= '4', n= 0;for (i in a) { n++;
> > alert(i+a[i]); };alert(n+' !== '+a.length);
>
> > Is it predictable in this case ? the order of 'i', I mean ?
>
> What do you mean by 'predictable' ?
>
> javascript:a=['0',,,,,,,,'8'], a[4]= '4';for(i in a)
> if(a[i])alert('elem.t #'+i+' = '+a[i]);
>

When I run this in webkit r36882 the last (4th) alert reads:

'elem.t #peek = function () {return this[this.length-1]}' ???

What (the hell) is that ??

--
Jorge.

Jorge

unread,
Sep 26, 2008, 9:04:41 PM9/26/08
to
On Sep 27, 2:26 am, Conrad Lender <crlen...@yahoo.com> wrote:
> On 2008-09-27 01:56, Jorge wrote:
>
> > On Sep 26, 7:53 pm, Thomas 'PointedEars' Lahn <PointedE...@web.de>
> ..
> >> > javascript:a=['0',,,,,,,,'8'], a[4]= '4', n= 0;for (i in a) { n++;
> >> > alert(i+a[i]); };alert(n+' !== '+a.length);
>
> >> > Is it predictable in this case ? the order of 'i', I mean ?
>
> >> No; read ES3F, 12.6.4.
>
> > That's what I thought, but as SAM said, however hard I try, it always
> > shows them in the right order.
>
> For one thing, there's this possibility:
>
> var a = ['0', '1'];
> a.blah = "ho hum";
> a.push('2', '3');
> for (var i in a) {
>     document.write(i + ": " + a[i] + "<br>");
>
> }
>

Yes, but still sorts it well.
This one instead... :-(

javascript:a=[0,,2];a[1]=undefined;for (i in a) { alert(i+':'+a[i]) };

--
Jorge.

Conrad Lender

unread,
Sep 26, 2008, 9:55:44 PM9/26/08
to
On 2008-09-27 03:04, Jorge wrote:
>> var a = ['0', '1'];
>> a.blah = "ho hum";
>> a.push('2', '3');
>> for (var i in a) {
>> document.write(i + ": " + a[i] + "<br>");
>>
>> }
>
> Yes, but still sorts it well.

For custom values of "well".
It sorts "blah" between index 1 and 2 (FF2).

> This one instead... :-(
>
> javascript:a=[0,,2];a[1]=undefined;for (i in a) { alert(i+':'+a[i]) };

I don't get it. What does this display in your browser?
All it does in FF2 is alert:

0:0
1:undefined
2:2

Which is what you would expect, I guess.


- Conrad

Jorge

unread,
Sep 26, 2008, 10:08:45 PM9/26/08
to
On Sep 27, 3:55 am, Conrad Lender <crlen...@yahoo.com> wrote:
> On 2008-09-27 03:04, Jorge wrote:
>
> >> var a = ['0', '1'];
> >> a.blah = "ho hum";
> >> a.push('2', '3');
> >> for (var i in a) {
> >>     document.write(i + ": " + a[i] + "<br>");
>
> >> }
>
> > Yes, but still sorts it well.
>
> For custom values of "well".
> It sorts "blah" between index 1 and 2 (FF2).

Ah, :-( then.

> > This one instead... :-(
>
> > javascript:a=[0,,2];a[1]=undefined;for (i in a) { alert(i+':'+a[i]) };
>
> I don't get it. What does this display in your browser?
> All it does in FF2 is alert:
>
>   0:0
>   1:undefined
>   2:2
>
> Which is what you would expect, I guess.
>

No, see, here a[1] === undefined as well, but it's not listed :

javascript:a= [0,,2];for (i in a) { alert(i+':'+a[i]) };

I was thinking that the for..in would help in transversing a sparse
array (an array with 'holes'), but that's not the case.

--
Jorge.

dhtml

unread,
Sep 28, 2008, 9:19:54 PM9/28/08
to
Jorge wrote:
> On Sep 27, 3:55 am, Conrad Lender <crlen...@yahoo.com> wrote:
>> On 2008-09-27 03:04, Jorge wrote:
>>
>>>> var a = ['0', '1'];
>>>> a.blah = "ho hum";
>>>> a.push('2', '3');
>>>> for (var i in a) {
>>>> document.write(i + ": " + a[i] + "<br>");
>>>> }
>>> Yes, but still sorts it well.
>> For custom values of "well".
>> It sorts "blah" between index 1 and 2 (FF2).
>
> Ah, :-( then.
>
>>> This one instead... :-(
>>> javascript:a=[0,,2];a[1]=undefined;for (i in a) { alert(i+':'+a[i]) };
>> I don't get it. What does this display in your browser?
>> All it does in FF2 is alert:
>>
>> 0:0
>> 1:undefined
>> 2:2
>>
>> Which is what you would expect, I guess.
>>
>
> No, see, here a[1] === undefined as well, but it's not listed :
>

above, the value of the "1" property that exists is undefined.

> javascript:a= [0,,2];for (i in a) { alert(i+':'+a[i]) };
>

No "1" property exists. When attepting to get the "1" property, it is
not found and so undefined is returned.


> I was thinking that the for..in would help in transversing a sparse
> array (an array with 'holes'), but that's not the case.
>

Which browser? FF 3.0?

javascript: alert(1 in [0,,2])

FF3.1
false

FF 3.0.1:
true

That was a bug that got fixed.

> --
> Jorge.

Jorge

unread,
Sep 29, 2008, 4:15:03 PM9/29/08
to

Hmmm, thanks.

--
Jorge.

Thomas 'PointedEars' Lahn

unread,
Sep 30, 2008, 6:16:00 AM9/30/08
to
Conrad Lender wrote:
> Jorge wrote:

> > Thomas 'PointedEars' Lahn wrote:
> >> > javascript:a=['0',,,,,,,,'8'], a[4]= '4', n= 0;for (i in a) { n++;
> >> > alert(i+a[i]); };alert(n+' !== '+a.length);
> >> >
> >> > Is it predictable in this case ? the order of 'i', I mean ?
> >> No; read ES3F, 12.6.4.
> > That's what I thought, but as SAM said, however hard I try, it always
> > shows them in the right order.
>
> [...] I'll bet my hat that Thomas can come up with a passage in

> the ECMAScript specs that says that object properties aren't guaranteed
> to be returned in any particular order in a for..in loop.

As I mentioned before, the Specification defines the algorithm for the
for-in statement, where it says:

| 12.6.4 The for-in Statement
|
| The production
| IterationStatement :
| for ( LeftHandSideExpression in Expression ) Statement
| is evaluated as follows:
|
| 1. Evaluate the Expression.
| 2. Call GetValue(Result(1)).
| 3. Call ToObject(Result(2)).
| 4. Let V = empty.
| 5. Get the name of the next property of Result(3) that doesn’t have
| the DontEnum attribute. If there is no such property, go to step
14.
| [...]
| 14. Return (normal, V, empty)

And:

| 4.2 Language Overview
|
| [...] An ECMAScript object is an unordered collection of properties
[...]

| 4.3.3 Object
|
| An object is a member of the type Object. It is an unordered
collection
| of properties [...]

| 8.6 The Object Type
|
| An Object is an unordered collection of properties. [...]


HTH

PointedEars

0 new messages