adding properties to primitive data types other than Array

前端 未结 2 1862
闹比i
闹比i 2021-01-19 09:41

I\'m not supposed to add elements to an array like this:

var b   = [];
b.val_1 = \"a\";
b.val_2 = \"b\";
b.val_3 = \"c\";

I can\'t use nati

2条回答
  •  借酒劲吻你
    2021-01-19 10:03

    Because arrays are treated as Objects by the language, you can see this by typing the following line of code:

    console.log(typeof []) // object
    

    But other types like number literals, string literals NaN ... etc are primitive types and are only wrapped in their object reprsentation in certain contexts defined by the language.

    If you want to add properties or methods to a number like that, then you can use the Number constructor like this:

    var num = new Number(1);
    num.prop_1 = "fdadsf";
    console.log(num.prop_1);
    

    Using the Number constructor returns a number object which you can see by typing the following line:

    console.log(typeof num); // object
    

    While in the first case:

    var num = 1;
    console.log(typeof num) // number
    

    EDIT 2: When you invoke a method on a number literal or string literal for instance, then that primitive is wrapped into its object representation automatically by the language for the method call to take place, for example:

    var num = 3;
    console.log(num.toFixed(3)); // 3.000
    

    Here num is a primitive variable, but when you call the toFixed() metohd on it, it gets wrapped to a Number object so the method call can take place.

    EDIT: In the first case, you created a string like this first var str = new String(), but then you changed it to str = "asdf" and then assigned the property str.var_1 = "1234".

    Of course, this won't work, because when you assigned str = "asdf", str became a primitive type and the Object instance that was originally created is now gone, and you can't add properties to primitives.

    In the second, it didn't output undefined like you said, I tested it in Firebug and everything worked correctly.

    EDIT 3:

    String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings.

    This is taken from MDN Documentation, when you use string like that var p = String(3) it becomes a conversion function and not a constructor and it returns a primitive string as you can see from the quote above.

    Regarding your second comment, I didn't understand how my comment has been defied, because if you try to console.log(p.pr) you'll get undefined which proves p is a primitive type and not an object.

提交回复
热议问题