简体   繁体   English

数组和对象是 Javascript 中唯一的非基元吗?

[英]Are Array's & Objects the only non-primitives in Javascript?

I've been doing a lot of research on this topic for over 2 weeks now and I'm only asking the question because MDN's documentation on mutability says only arrays and objects are not primitive values and of course that's true, they have reference values.我已经在这个主题上做了 2 个多星期的大量研究,我只是问这个问题,因为MDN 的可变性文档说只有数组和对象不是原始值,当然这是真的,它们有参考值。

However, I thought functions , string object , Date , and RegEx also had reference values because they are also non-primitives.但是,我认为functionsstring objectDateRegEx也有参考值,因为它们也是非原始的。 For example if we use slice() on a string primitive, javascript will automatically convert(reassign) it to a string object and now it's mutable as the word 'snow' becomes 'know' through reassignment.例如,如果我们在字符串原语上使用 slice(),javascript 将自动将其转换(重新分配)为字符串对象,现在它是可变的,因为单词“snow”通过重新分配变为“知道”。 This won't work with const because it disables reassignment.这不适用于const因为它禁用重新分配。

let word = 'snow'
console.log(word) // "snow"
word = `k${word.slice(1)}`
console.log(word) // "know"

So I'm guessing either MDN is wrong or a lot of other resources like dotnettricks and even a few javascript certifications guides are wrong...所以我猜要么是 MDN 是错误的,要么是很多其他资源,比如dotnettricks ,甚至一些 javascript 认证指南都是错误的......

MDN isn't wrong - functions, Date and RegEx are objects. MDN 没有错——函数、Date 和 RegEx都是对象。

Also, string is still primitive.此外,字符串仍然是原始的。

let a = 'snow';
let b = a;
a = 'know';
console.log(b); // snow

"strings" is primitive and new String("strings") is an object but in both cases the sequence of characters is immutable. "strings" 是原始的,而 new String("strings") 是一个对象,但在这两种情况下,字符序列都是不可变的。

in your example you didn't really mutate the string you just create a new string and assign it to the same variable在您的示例中,您并没有真正改变字符串,您只是创建了一个新字符串并将其分配给相同的变量

var primitiveString = 'hello';
var objectString = new String('hello');
var objectStringRef = objectString;

// string are primitives so you can not add properties to it
primitiveString.newProperty = "my property";

console.log(primitiveString.newProperty) // undefined

// You can add properties to String objects
objectString.newProperty = "my property";

console.log(objectString.newProperty) // "my property"

// and you can have a reference to a String object
console.log(objectStringRef.newProperty) // "my property"

// but both are immutable
primitiveString[0] = "p";
objectString[0] = "p";

console.log(primitiveString) // "hello"
console.log(objectStringRef.toString()) // "hello"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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