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.
> 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);
> 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:
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>
> "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);
On 24 sep, 03:48, SAM <stephanemoriaux.NoAd...@wanadoo.fr.invalid> wrote:
> 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
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.
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 ?
> 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);
> 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.
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.
> >>>> 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.
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. [...]