Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Eval: run a code string#270

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Closed
odsantos wants to merge37 commits intojavascript-tutorial:masterfromodsantos:fix-conflicts
Closed
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
37 commits
Select commitHold shift + click to select a range
15d0c57
Update article.md
HakaCodeJul 31, 2020
d0c9961
Merge pull request #1 from HakaCode/master
HakaCodeJul 31, 2020
3e66630
Revert "Update article.md"
HakaCodeJul 31, 2020
aa9bf40
Fix things and translate the summary of eval article
Jul 31, 2020
8de0cf3
Update article.md
Jul 31, 2020
e1237c2
Update article.md
Jul 31, 2020
514360d
Update article.md
Jul 31, 2020
e53e33a
Update task.md
Jul 31, 2020
ea04503
Merge branch 'master' into revert-1-master
Aug 1, 2020
bc970cb
Merge pull request #2 from ashuradev/revert-1-master
Aug 1, 2020
462fe29
Update article.md
HakaCodeAug 1, 2020
674bdd4
Merge pull request #3 from HakaCode/master
Aug 1, 2020
be6157f
Update article.md
HakaCodeAug 1, 2020
cb7e241
Update article.md
Aug 1, 2020
65ee8f0
Merge branch 'master' into fix-conflicts
Jan 31, 2021
b3ebc0d
Update 1-js/99-js-misc/02-eval/1-eval-calculator/task.md
May 19, 2021
dea981d
Update 1-js/99-js-misc/02-eval/article.md
May 19, 2021
627898f
Update 1-js/99-js-misc/02-eval/article.md
May 19, 2021
5589be2
Update 1-js/99-js-misc/02-eval/article.md
May 19, 2021
47c9e89
Update 1-js/99-js-misc/02-eval/article.md
May 19, 2021
9385f54
Update 1-js/99-js-misc/02-eval/article.md
May 19, 2021
80feedb
Update 1-js/99-js-misc/02-eval/article.md
May 19, 2021
e1cca32
Update 1-js/99-js-misc/02-eval/article.md
May 19, 2021
980f579
Update 1-js/99-js-misc/02-eval/article.md
May 19, 2021
75371f9
Update 1-js/99-js-misc/02-eval/article.md
May 19, 2021
32ce693
Update 1-js/99-js-misc/02-eval/article.md
May 19, 2021
05dd276
Update 1-js/99-js-misc/02-eval/article.md
May 19, 2021
3585e5a
Update 1-js/99-js-misc/02-eval/article.md
May 19, 2021
7680f57
Update 1-js/99-js-misc/02-eval/article.md
May 19, 2021
cf4d973
Update 1-js/99-js-misc/02-eval/article.md
May 19, 2021
26ffb20
Update 1-js/99-js-misc/02-eval/article.md
May 19, 2021
1f002e2
Update 1-js/99-js-misc/02-eval/article.md
May 19, 2021
3cc8dab
Update 1-js/99-js-misc/02-eval/article.md
May 19, 2021
2c95a88
Update article.md
odsantosMay 19, 2021
2bf304a
Update article.md
odsantosMay 19, 2021
8756ef0
Add solution translation
odsantosJan 20, 2023
3691f56
Merge branch 'master' into fix-conflicts
odsantosJan 20, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions1-js/99-js-misc/02-eval/1-eval-calculator/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
Let's use `eval`to calculate the maths expression:
Vamos usar `eval`para calcular a expressão matemática:

```js demo run
let expr = prompt("Type an arithmetic expression?", '2*3+2');
let expr = prompt("Escreva uma expressão aritmética?", '2*3+2');

alert( eval(expr) );
```

The user can input any text or code though.
Contudo, o usuário pode dar entrada a qualquer texto ou código.

To make things safe, and limit it to arithmetics only, we can check the`expr`using a [regular expression](info:regular-expressions),so that it only may contain digits and operators.
Para tornar as coisas seguras, e limitar a entrada a apenas aritméticas, nós podemos checar`expr`usando uma [expressão regular](info:regular-expressions),de forma que apenas possa conter dígitos e operadores.
6 changes: 3 additions & 3 deletions1-js/99-js-misc/02-eval/1-eval-calculator/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,10 +2,10 @@ importance: 4

---

#Eval-calculator
#Calculadora-eval

Create a calculator that prompts for an arithmetic expression and returns its result.
Crie uma calculadora que solicite uma expressão aritmética e retorne seu resultado.

There's no need to check the expression for correctness in this task. Just evaluate and return the result.
Não há necessidade de verificar se a expressão está correta nesta tarefa. Apenas avalie e retorne o resultado.

[demo]
74 changes: 37 additions & 37 deletions1-js/99-js-misc/02-eval/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,25 @@
# Eval:run a codestring
# Eval:execute umastring de código

The built-in`eval`function allows to execute astringof code.
A função interna`eval`permite executar umastringde código.

The syntax is:
A sintaxe é:

```js
letresult = eval(code);
letresultado = eval(code);
```

For example:
Por exemplo:

```js run
let code = 'alert("Hello")';
eval(code); //Hello
let code = 'alert("Olá")';
eval(code); //Olá
```

A stringof code may be long, contain line breaks, function declarations, variables and so on.
A stringde código pode ser longa, conter quebras de linha, declarações de função, variáveis e assim por diante.

The result of `eval`is the result of the last statement.
O resultado de `eval`é o resultado da última instrução.

For example:
Por exemplo:
```js run
let value = eval('1+1');
alert(value); // 2
Expand All@@ -30,7 +30,7 @@ let value = eval('let i = 0; ++i');
alert(value); // 1
```

The eval'ed code is executed in the current lexical environment, so it can see outer variables:
O código avaliado é executado no ambiente léxico atual, para que ele possa ver variáveis externas:

```js run no-beautify
let a = 1;
Expand All@@ -46,69 +46,69 @@ function f() {
f();
```

It can change outer variables as well:
Também pode alterar variáveis externas:

```js untrusted refresh run
let x = 5;
eval("x = 10");
alert(x); // 10,value modified
alert(x); // 10,valor modificado
```

In strict mode,`eval`has its own lexical environment. So functions and variables, declared insideeval,are not visible outside:
No modo estrito, o`eval`possui seu próprio ambiente léxico. Portanto, funções e variáveis, declaradas dentro deeval,não são visíveis fora:

```js untrusted refresh run
//reminder: 'use strict'is enabled in runnable examples by default
//lembrete: 'use strict'está ativado em exemplos executáveis por padrão

eval("let x = 5; function f() {}");

alert(typeof x); // undefined (no such variable)
//function f is also not visible
alert(typeof x); // undefined (não existe tal variável)
//a função f também não é visível
```

Without `use strict`, `eval`doesn't have its own lexical environment, so we would see`x`and `f`outside.
Sem `use strict`, `eval`não possui seu próprio ambiente léxico, portanto veríamos`x`e`f`fora.

##Using "eval"
##Usando "eval"

In modern programming `eval`is used very sparingly. It's often said that"evalis evil".
Na programação moderna `eval`é usado com moderação. Costuma-se dizer que"evalé mau".

The reason is simple: long, long time ago JavaScriptwas a much weaker language, many things could only be done with`eval`.But that time passed a decade ago.
O motivo é simples: há muito, muito tempo, o JavaScriptera uma linguagem muito mais fraca, muitas coisas só podiam ser feitas com o`eval`.Mas esse tempo passou há uma década atrás.

Right now, there's almost no reason to use`eval`.If someone is using it, there's a good chancethey can replace it with a modern language construct or a [JavaScript Module](info:modules).
No momento, quase não há razão para usar o`eval`.Se alguém o estiver usando, há uma boa chancede o poder substituir por uma construção de linguagem moderna ou um [módulo JavaScript](info:modules).

Please note that its ability to access outer variables has side-effects.
Observe que sua capacidade de acessar variáveis externas tem efeitos colaterais.

Code minifiers (tools used beforeJSgets to production, to compress it) rename local variables into shorter ones (like `a`, `b` etc) to make the code smaller. That's usually safe, but not if`eval`is used, as local variables may be accessed from eval'ed code string. So minifiers don't do that renaming for all variables potentially visible from`eval`.That negatively affects code compression ratio.
Os minificadores de código (ferramentas usadas antes deJSchegar à produção, para compactá-lo) renomeiam as variáveis locais por outras mais curtas para otimização. Isso geralmente é seguro, mas não se o`eval`for usado, pois pode fazer referência a elas. Portanto, os minificadores não renomeiam todas as variáveis que possam ser visíveis em`eval`.Isso afeta negativamente a taxa de compactação de código.

Using outer local variables inside`eval`is also considered a bad programming practice, as it makes maintaining the code more difficult.
Usar variáveis locais externas dentro de`eval`é uma prática ruim de programação, pois dificulta a manutenção do código.

There are two ways how to be totally safe from such problems.
Existem duas maneiras de se proteger totalmente de tais problemas.

**If eval'ed code doesn't use outer variables, please call`eval`as `window.eval(...)`:**
**Se o código avaliado não usa variáveis externas, chame`eval`como `window.eval(...)`:**

This way the code is executed in the global scope:
Dessa forma, o código é executado no escopo global:

```js untrusted refresh run
let x = 1;
{
let x = 5;
window.eval('alert(x)'); // 1 (global variable)
window.eval('alert(x)'); // 1 (variável global)
}
```

**If eval'ed code needs local variables, change `eval`to `new Function`and pass themasarguments:**
**Se o código avaliado precisar de variáveis locais, mude `eval`para `new Function`e passe-ascomo argumentos:**

```js run
let f = new Function('a', 'alert(a)');

f(5); // 5
```

The`new Function`construct is explained in the chapter<info:new-function>.It creates a function from a string,also in the global scope. So it can't see local variables. But it's so much clearer to pass them explicitly as arguments, like in the example above.
A construção`new Function`é explicada no capítulo<info:new-function>.Ela cria uma função a partir de uma string,também no escopo global. Portanto, ele não pode ver variáveis locais. Mas é muito mais claro passá-las explicitamente como argumentos, como no exemplo acima.

##Summary
##Resumo

A call to `eval(code)`runs the stringof code and returns the result of the last statement.
-Rarely used in modernJavaScript, as there's usually no need.
-Can access outer local variables. That's considered bad practice.
-Instead, to `eval`the code in the global scope, use `window.eval(code)`.
-Or, if your code needs some data from the outer scope, use `new Function`and pass it as arguments.
Uma chamada para `eval(code)`executa a stringde código e retorna o resultado da última instrução.
-Raramente usado noJavaScript moderno, pois geralmente não há necessidade.
-Pode acessar variáveis locais externas. Isso é considerado uma má prática.
-Em vez disso, para `eval`o código no escopo global, use `window.eval(code)`.
-Ou, se o seu código precisar de alguns dados do escopo externo, use `new Function`e passe-os como argumentos.

[8]ページ先頭

©2009-2025 Movatter.jp