Elementos de un array

L

LuisDavid

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.
 
S

SAM

LuisDavid a écrit :
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.


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);
 
T

Thomas 'PointedEars' Lahn

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

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

is also possible. See said:
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);

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
 
S

SAM

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.length>k.length) k = lista;
alert('El elemento más largo es : '+k);
 
L

LuisDavid

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.length>k.length) k = lista;
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);
//var lista = ["uno","tres","cinco","tres"];
var k = '';
for(i in lista) if(lista.length>k.length) k = lista;
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.
 
J

Jorge

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); };alert(n+' !== '+a.length);

Is it predictable in this case ? the order of 'i', I mean ?
 
J

Jorge

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,
 
S

SAM

Le 9/25/08 7:14 PM, Jorge a écrit :
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); };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)alert('elem.t #'+i+' = '+a);

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); };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); };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); };alert('n =
'+n+'\na.length = '+a.length+'\nis n = a.length ? '+(n == a.length));
 
S

SAM

Le 9/25/08 5:51 PM, LuisDavid a écrit :
var lista = ["uno","dos","tres","cuatro",'cinco','seis'];
var k = '';
for(i in lista) if(lista.length>k.length) k = lista;
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.length>k.length)k=lista;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);
if(lista.length>k.length)k=lista;}alert('mas largo = '+k);

//var lista = ["uno","tres","cinco","tres"];
var k = '';
for(i in lista) if(lista.length>k.length) k = lista;
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.length>k.length)k=lista;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);
if(lista.length>k.length)k=lista;}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);


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.length>k.length) k = lista;
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.length>k.length)k=lista;alert(k);

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

forces to set 'lista' to an array
 
T

Thomas 'PointedEars' Lahn

Jorge said:
SAM said:
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); };alert(n+' !== '+a.length);

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


No; read ES3F, 12.6.4.


PointedEars
 
J

Jorge

Le 9/25/08 7:14 PM, Jorge a écrit :
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); };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...)
 
J

Jorge

Le 9/25/08 7:14 PM, Jorge a écrit :
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); };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)alert('elem.t #'+i+' = '+a);


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 ??
 
J

Jorge

On Sep 26, 7:53 pm, Thomas 'PointedEars' Lahn <[email protected]> ..
javascript:a=['0',,,,,,,,'8'], a[4]= '4', n= 0;for (i in a) { n++;
alert(i+a); };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 + "<br>");

}


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

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

Jorge

var a = ['0', '1'];
a.blah = "ho hum";
a.push('2', '3');
for (var i in a) {
    document.write(i + ": " + a + "<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 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 was thinking that the for..in would help in transversing a sparse
array (an array with 'holes'), but that's not the case.
 
D

dhtml

Jorge said:
var a = ['0', '1'];
a.blah = "ho hum";
a.push('2', '3');
for (var i in a) {
document.write(i + ": " + a + "<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 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) };


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.
 
J

Jorge

Jorge said:
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 + "<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 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) };


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.


Hmmm, thanks.
 
T

Thomas 'PointedEars' Lahn

Conrad said:
Jorge said:
Thomas said:
javascript:a=['0',,,,,,,,'8'], a[4]= '4', n= 0;for (i in a) { n++;
alert(i+a); };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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top