Javascript将值赋给基元 [英] Javascript assigning value to primitive
问题描述
如果JavaScript很容易在基元和对象之间强制转换,为什么向它添加属性会导致未定义?
If JavaScript will readily coerce between primitives and objects why adding properties to it results to undefined??
var a = "abc";
var b = a.length
console.log(b)//outputs 3
强制允许我为原语分配值吗?如果没有原因?
Does coercion allow me to assign values to primitives?If not why ?
推荐答案
强制允许我为原语分配值?
Does coercion allow me to assign values to primitives?
是的。原语包装在一个对象中,并在其上创建一个属性。不会抛出任何异常。
Yes. The primitive is wrapped in an object, and a property is created on that. No exception will be thrown.
为什么向它添加属性会导致未定义?
why adding properties to it results to undefined?
添加本身确实会产生价值。
The adding itself does result in the value.
var str = "abc";
console.log(str.someProperty = 5); // 5
然而,你要求的是从原语中获取属性。这将返回 undefined
,因为基元包含在新包装器对象中 - 而不是您为其分配属性的对象:
Yet, what you're asking for is getting a property from a primitive. This will return in undefined
since the primitive is wrapped in a new wrapper object - not the one which you assigned the property on:
console.log(str.someProperty); // undefined
它仅适用于 .length $等特殊属性c $ c>使用该对象创建的,或者是继承的
slice
或 charAt
方法(参见这些文档。
It only works for special properties like .length
that are created with the object, or inherited ones like slice
or charAt
methods (see the docs for those).
如果你想要这样的东西,你需要明确地创建包装器对象并将其存储在某个地方:
If you wanted such a thing, you'd need to create the wrapper object explicitly and store it somewhere:
var strObj = new String("abc");
strObj.someProperty = 5;
console.log(strObj.someProperty); // 5
// coercion and the `toString` method will even make the object act like a string
console.log(strObj + "def"); // "abcdef"
这篇关于Javascript将值赋给基元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!