简体   繁体   中英

Why do these functions don't work

I don't understand why only the stFunction() works? Why I got the syntax error (unexpected token ".") at the ndFunction() and what's wrong with rdFunction() ? Thank you for help

function stFunction() {
    var x = document.getElementById("id1");
    x.value = x.value.toUpperCase();
}
function ndFunction() {
    var y.value = document.getElementById("id2").value.toUpperCase();
}
function rdFunction() {
    var y = {};
    y.value = document.getElementById("id3").value.toUpperCase();
}

Your ndFunction isn't working because y doesn't exist when you try to set it's property. As for rdFunction as long as your element exists and has a value it should work just fine.

function ndFunction() {
    var y = {},
        y.value = document.getElementById("id2").value.toUpperCase();
}

Why I got the syntax error (unexpected token ".") at the ndFunction()

When you write var y.value = document.getElementById("id2").value.toUpperCase(); , you are actually defining a variable named y.value which is not a valid variable name ( https://mothereff.in/js-variables#y.value ). The dot is a property accessors, that is why you're getting the syntax error unexpected token "." . It is trying to access the property named value for the variable y that you didn't define before.

and what's wrong with rdFunction()?

Nothing is wrong with rdFunction() . You are creating an object named y using an object initializer . Then you are defining the property named value for this object and the value of the property value will be document.getElementById("id3").value.toUpperCase(); . Try a console.log(y) at the end of rdFunction() . You'll see that everything works fine. Note that you also could have defined the property value like this

var y = {};
y['value'] = document.getElementById("id3").value.toUpperCase();

@Dontfeedthecode has the point. If stFunction works, you can do the same as stFunction for ndFunction :D on ndFunction:

function ndFunction() {
    var y = document.getElementById("id2");
    y.value = y.value.toUpperCase();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM