Home>

Beginning JavaScript.
I would appreciate it if you could explain it because there was an unfamiliar description while browsing human code.

This is a script for number selection that is often used on EC sites.

<form name = "form">
<span onclick = "box_spin ('box1', 'm');">-</span>
<input type = "text" name = "box1" value = "1" size = "3" maxlength = "3">
<span onclick = "box_spin ('box1', 'p');">+</span>
</form>
function box_spin (name, type) {
    var itemValue;
↓ Here
    itemValue = document.form ['' + name] .value;
~ Omitted ~
}

↓ I don't know here.
You can see that "form" is the name of the form and "name" is the name of the input,
What does single quotation + mean?

document.form ['' + name]

We did a lot of research but couldn't find it.
I can understand the purpose, but I don't know what technique is used.
Also, it seems that it is written abbreviated, but is such a description common in business?
I would appreciate it if you could explain.

  • Answer # 1

    ''itself is aempty string.

    By concatenating an empty string and another, it means "convert the concatenated to a string".

  • Answer # 2

    You can guess that the purpose is to cast a number to a string as it already exists
    The example source description is too old. (Probably about 15-20 years ago)
    Shouldn't be helpful

    Assuming an instruction like "box_spin (100,'m')"
    document.form (ie form named form)
    If name ="100"is input, it cannot be referenced
    So it ’s just a wasteful casting process

  • Answer # 3

    + operator The

    +operator takes the String type as an argument, and the other has the operation of finally converting it to the String type by the procedure "Convert to Primitive type → Convert to String type". The

    '' + foo

    Although it is often written in short coders, it is essentially different from "Conversion to String type" because it uses a primitive type once.
    Property Accessors

    http://www.ecma-international.org/ecma-262/9.0/#sec-property-accessors

    itemValue = document.form ['' + name] .value;

    With this syntax, there is no need to explicitly convert to String type.
    Property accessor is a specification to convert to String type if the key is not Symbol type.

    Re: Mr. akamotosan

  • Answer # 4

    I think you are casting so that the type of name is a string even if it is a number.