Created
January 22, 2012 16:07
-
-
Save Diullei/1657533 to your computer and use it in GitHub Desktop.
Exemplo de criação de uma função que utiliza o objeto arguments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function strFormat() { | |
| // Note que o objeto arguments não é um array e por isso vamos criar um | |
| // array com os argumentos passados para a função. Assim fica mais fácil | |
| // utilizar os métodos nativos do do array. | |
| var list = Array.prototype.slice.call(arguments); | |
| // Como esta função será introduzida via protótipo no objeto String do | |
| // JavaScript iremos armazenar o valor da string a ser manipulada recuperando | |
| // o próprio contexto desta função | |
| var str = this; | |
| // O trecho de código abaixo executa a substituição dos parâmetros na string 'str' | |
| for(var i = 0; i<list.length; i++) { | |
| var found = str.indexOf('{' + i + '}'); | |
| while(found != -1) { | |
| str = str.replace('{' + i + '}', list[i]) | |
| found = str.indexOf('{' + i + '}'); | |
| } | |
| } | |
| // retorna a string alterada com os argumentos inseridos | |
| return str; | |
| } | |
| // Crio uma função format no objeto String referenciando a função que acabamos de criar | |
| String.prototype.format = strFormat; | |
| // Executando a função | |
| console.log('animais: {0} {1} {0} {2} {3}'.format('gato', 'cachorro', 'galinha', 'passarinho')); | |
| // => animais: gato cachorro gato galinha passarinho |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment