Primitive - MDN Web Docs Glossary: Definitions of Web-related terms 编辑
In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods. There are 6 primitive data types: string, number, bigint, boolean, undefined, and symbol. There also is null, which is seemingly primitive, but indeed is a special case for every Object
: and any structured type is derived from null
by the Prototype Chain.
Most of the time, a primitive value is represented directly at the lowest level of the language implementation.
All primitives are immutable, i.e., they cannot be altered. It is important not to confuse a primitive itself with a variable assigned a primitive value. The variable may be reassigned a new value, but the existing value can not be changed in the ways that objects, arrays, and functions can be altered.
Example
This example will help you understand that primitive values are immutable.
JavaScript
// Using a string method doesn't mutate the string
var bar = "baz";
console.log(bar); // baz
bar.toUpperCase();
console.log(bar); // baz
// Using an array method mutates the array
var foo = [];
console.log(foo); // []
foo.push("plugh");
console.log(foo); // ["plugh"]
// Assignment gives the primitive a new (not a mutated) value
bar = bar.toUpperCase(); // BAZ
A primitive can be replaced, but it can't be directly altered.
Primitive wrapper objects in JavaScript
Except for null
and undefined
, all primitive values have object equivalents that wrap around the primitive values:
String
for the string primitive.Number
for the number primitive.BigInt
for the bigint primitive.Boolean
for the boolean primitive.Symbol
for the symbol primitive.
The wrapper's valueOf()
method returns the primitive value.
Learn more
General knowledge
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论