Uncaught SyntaxError: Unexpected token var

0

I'm doing a simple test with RegExp in JSFiddle and I do not understand why

  

Uncaught SyntaxError: Unexpected token var

See: link

Code:

<input type="text" id="entrada"></input>
<button id="botao">Testar</button>
$("#botao").click(function () {
    if (var m = $("#entrada").val().match(/\d-\d/g)) {
        for (var i = 0; i < m.length(); i++) {
            alert(m[i]);
        }
    } else {
        alert("no match");
    }
});

Update

After the suggestion of @Sergio I'm having another error:

  

Uncaught TypeError: number is not a function

In this line here: for (i = 0; i < m.length(); i++) {

Updated JSFiddle: link

    
asked by anonymous 18.06.2014 / 15:02

1 answer

2

You can not define variables within a if() , the reason this is not possible is that a variable definition always returns undefined and then your if would always fail.

Use this:

$("#botao").click(function () {
    var m; // defina a variável fora do if para estar defenida e não exportar para o espaço global
    if (m = $("#entrada").val().match(/\d-\d/g)) {
    
18.06.2014 / 15:05