Can JavaScript variables hold multiple data types?
This article mainly explains the "JavaScript variables can save a variety of data types", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in-depth, together to study and learn "JavaScript variables can save multiple data types" bar!
JavaScript variables can hold multiple data types: numeric values, string values, arrays, objects, and so on:
Var length = 7; / / number
Var lastName = "Gates"; / / string
Var cars = ["Porsche", "Volvo", "BMW"]; / / Array
Var x = {firstName: "Bill", lastName: "Gates"}; / / object
The concept of data types
In the process of programming, data type is an important concept.
In order to be able to manipulate variables, it is important to understand the data type.
Without a data type, the computer cannot safely solve the problem:
Var x = 911 + "Porsche"
Does it make sense to add 911 to "Volvo"? Will this make a mistake or will it produce a result?
JavaScript will handle the above example like this:
Var x = "911" + "Porsche"
When a numeric value is added to a string, JavaScript treats the numeric value as a string.
Example
Var x = 911 + "Porsche"
Example
Var x = "Porsche" + 911
JavaScript evaluates the expression from left to right. Different orders produce different results:
JavaScript:
Var x = 911 + 7 + "Porsche"
Results:
918Porsche
JavaScript:
Var x = "Porsche" + 911 + 7
Results:
Porsche9117
In the first example, JavaScript treats 911 and 7 as numeric values until he meets "Porsche".
In the second example, because the first Operand is a string, all operands are treated as strings.
Thank you for your reading, the above is the content of "JavaScript variables can save multiple data types", after the study of this article, I believe you can save multiple data types of JavaScript variables have a deeper understanding of this problem, the specific use of the situation also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!