Jump to content


Photo

In_array


  • Faça o login para participar
8 replies to this topic

#1 Klaus

Klaus

    @ ubuntu jaunty

  • Ex-Admins
  • 7924 posts
  • Sexo:Masculino
  • Localidade:127.0.0.1

Posted 13/07/2005, 09:47

Sintaxe: in_array (texto_procurado, matriz_para_busca);
Retorno: true caso encontre, false caso não encontre.
Descrição: Exatamente igual ao funcionamento da função in_array do PHP, retornando true ou false, caso encontre ou não o valor pesquisado na matriz fornecida.
Explicação adicional: http://klauspaiva.co...avascript.xhtml

Função:

function in_array (valor, matriz) {
  var texto = "¬" + matriz.join("¬") + "¬";
  var er = new RegExp ("¬" + valor + "¬", "gim");
  return ( (texto.match (er)) ? true : false );
}


Exemplo de utilização:

<script type="text/javascript" src="./in_array.js"></script>

<script type="text/javascript">
  var exemplo = ['teste', '123', '12', 'teste-dois', 'um-teste'];
  var achou = in_array ("teste", exemplo);
  alert (achou);
</script>


http://creativecommo.../by/2.0/deed.pt =)

-----

No JS 1.5 existe a implementação para a função indexOf em Arrays também. Porém, isso ainda não é constante na maioria dos browsers.

http://developer-tes...s:Array:indexOf
Klaus Paiva
Conheça também: Taperás

#2 bimonti

bimonti

    Super Veterano

  • Usuários
  • 2654 posts
  • Sexo:Masculino

Posted 13/09/2006, 16:56

Só um complementinho ae, eu tava precisando usar algo parecido mas em uma matriz multidimensional:

var dias = 
	[
	['12','Teste'],
	['15','Teste2'],
	['18','Teste3']
	];
	
function in_array(value){
	for(x in dias){
		if(dias[x].indexOf(value) != -1){
			return x+" "+dias[x].indexOf(value);
		}
	}
}
Array.prototype.in_array = in_array;
alert(dias.in_array('15'));

Tem exemplo de uso na função, não testei muito, funcionou para meu propósito e creio que irá funcionar em outros também. No exemplo eu já apliquei a função como método do objeto Array, é só chamar daí pra frente como método. :P
WebFórum - Equipe de Desenvolvimento - Monitor
Posted Image
Yeah I do have some stories, and it's true I want all the glory ...

#3 Paulo Freitas

Paulo Freitas

    ××××××× LRU #456504 ××××××× ××××××× LRM #364686 ×××××××

  • Ex-Admins
  • 5612 posts
  • Sexo:Masculino
  • Localidade:Campinas - SP

Posted 13/09/2006, 17:06

Dentro da função tu podia ter colocado this ao invés de dias, he he he... :assobio:

Imagino que haverá gente que não conseguirá adaptar por isso... :ponder:

Fiz uma adaptação... :D

<script type="text/javascript">
var vetor = [
	['12', 'Teste'],
	['15', 'Teste2'],
	['18', 'Teste3'],
];

Array.prototype.in_array = function (index, value)
{
	for (item in this) {
		if (this[item][index].indexOf(value) != -1) {
			return true;
		}
	}

	return false;
}

alert(vetor.in_array(0, '15'));
alert(vetor.in_array(1, 'Teste3'));
</script>
[]’s :DAté mais

#4 bimonti

bimonti

    Super Veterano

  • Usuários
  • 2654 posts
  • Sexo:Masculino

Posted 13/09/2006, 18:50

alert(vetor.in_array(1, 'xyz')); ?? <_<

Edit ------>

Dá um erro muito sinistro de JavaScript usando for...in quando não existe a string buscada na matriz. Usando um for normal funciona, já não é a primeira vez que eu tenho esse problema estranho com o for...in. E não notei o erro porque usei a função pra buscar dados de uma matriz em outra, então alguma resultado igual seria encontrado. E a função que eu fiz não é muito parecida com a do PHP, o JavaScript anda meio pobre de funções pra matrizes, várias tem que criar na mão, nisso o PHP é bem mais prático (ou será que eu acostumei mal ??).

O real objetivo da minha função seria dar uma implementado no uso do método indexOf em matrizes, porque em matriz multidimensional indexOf não faz a busca, e pra deixar o post melhorzinho eu dei uma alterada na função, veja ae Paulo Freitas o que achou. ;)

<script type="text/javascript">
var dias =
	[
	['12','Teste'],
	['15','Teste2'],
	['18','Teste3'],
	"20"
	];
	
Array.prototype.in_array = function(value){
	for(var x=0; x<this.length; ++x){
		if(typeof(this) != "object"){
			if(this.indexOf(value) != -1){
				return true;
			}
		} else{
			for(var y=0; y<this.length; ++y){
				if(this[y].indexOf(value) != -1){
					return true;
				}
			}
		}
	}
	return false;
}
alert(dias.in_array('20'));
</script>

Edição feita por: bimonti, 13/09/2006, 19:39.

WebFórum - Equipe de Desenvolvimento - Monitor
Posted Image
Yeah I do have some stories, and it's true I want all the glory ...

#5 Miguceamma

Miguceamma

    MiguPenjisse

  • Usuários
  • 13201 posts

Posted 26/09/2017, 20:44

Viagra Naturale Femminile cialis price Controindicazioni Levitra
Kamagra Illegal Cialis Basso Prezzo Acquista Cialis On Line cialis Viagra Generique Pas Viagra Precio En La Farmacia Acheter Priligy En Ligne
Buy Kamagra Oral Jelly Australia Onlinepharmacy24 cialis Acheter Kamagra Ligne Cialis Media Pastilla

#6 Miguceamma

Miguceamma

    MiguPenjisse

  • Usuários
  • 13201 posts

Posted 30/10/2017, 20:08

Mexico Viagra Online 200 Mg Viagra Sale Medical Amoxil Antibiotics online pharmacy Efficacite Viagra Cialis Levitra Ricetta Medica Prix Amoxil En Pharmacie
Viagra In Farmacia Senza Ricetta Cialis 82 viagra Acheter Levitra Generique 20mg Acheter Viagra Quebec
Lioresal Novartis buy viagra online Cialis Terapia
Viagra Rezeptfrei Kaufen Apotheke Depakote viagra online pharmacy isotretinoin in us mastercard accepted Amoxicillin Dosaging
Cialis Effet Jeune Cialis Pas Cher En France viagra online pharmacy Levitra Generico On Line Kamagra In Usa
Mexican Pharmacies Viagra Gro?En viagra online Propecia Y Embarazo Order Viagra Online Female
Mejor Cialis 10 O 20 Mg Viagra Hollande buy cialis Amitriptyline No.Script Levitra Buying
Costo Cialis O Viagra viagra online Viagra Generique Sans Ordonnance

#7 Miguceamma

Miguceamma

    MiguPenjisse

  • Usuários
  • 13201 posts

Posted 16/09/2022, 15:04

Whether this is indicative of the successful properties of this combination or the result of limited use is not clear. doxycycline 100mg price Intralesional injections of 2- 10 mg mL 18 of triamcinolone acetonide can be used at monthly intervals.

#8 Miguceamma

Miguceamma

    MiguPenjisse

  • Usuários
  • 13201 posts

Posted 16/12/2022, 05:19

Effects of Schisandra sphenanthera extract on the pharmacokinetics of midazolam in healthy volunteers letrozole vs tamoxifen Moreover, the allergenic potency of Cas9 in gene therapies in humans remain unknown therefore it gives a great opportunity to the researcher for perusing potential solution against such issues

#9 JeffMalm

JeffMalm

    Super Veterano

  • Usuários
  • 12254 posts
  • Sexo:Feminino
  • Localidade:Mount Carey

Posted 17/01/2023, 04:30

Bull Soc Belge Ophtalmol 2012; 319 29 33 tamoxifen and uterine cancer for the Petites Cellules Group 1994 Subcutaneous heparin treatment increases survival in small cell lung cancer




1 user(s) are reading this topic

0 membro(s), 1 visitante(s) e 0 membros anônimo(s)

IPB Skin By Virteq