Heim > Web-Frontend > js-Tutorial > Hauptteil

String gegen String

Mary-Kate Olsen
Freigeben: 2024-10-15 14:24:01
Original
230 Leute haben es durchsucht

string vs String

string

Lowercase string is a primitive data type in JavaScript.

Strings created with this type are not objects, but JavaScript automatically wraps them with a String object (this is called "boxing").

let imAString = "hello";
console.log(typeof imAString); // "string"
Nach dem Login kopieren

String

Uppercase String is a constructor function that creates String objects, an object wrapper around a string primitive.

When you use the String constructor with new, you get a String object rather than a primitive string

String objects are not necessary unless you need to use them as objects explicitly.

let imAStringObject = new String("hello");
console.log(typeof imAStringObject); // "object"
Nach dem Login kopieren

Differences

string String
type primitive Object
Memory lightweight and stored by value heavyweight, stored as object
methods get converted to String object temporarily has access to String methods like .charAt()
Comparing Values by values by reference

When to use string/String?

Use string (primitive) in almost all cases. It is more efficient, simpler, and JavaScript automatically provides methods when needed.

Use String (object) only when you specifically need an object with additional properties or when you want to use instanceof checks, though this is rare in practice.


That's it! Thank you for reading this far. Till next time!

Das obige ist der detaillierte Inhalt vonString gegen String. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!