Home  >  Article  >  Web Front-end  >  There are several types in javascript

There are several types in javascript

青灯夜游
青灯夜游Original
2022-09-30 15:37:098064browse

There are 9 data types: 1. String type, which is a piece of text wrapped in quotation marks; 2. Numeric type, used to define values; 3. Boolean type, with only two values; 4. Null Type, which represents an "empty" value, that is, there is no value; 5. Undefined type, which represents undefined; 6. Symbol type, which represents a unique value; 7. Object type, which is an unordered set of keys and values. Collection; 8. Array type, which is a collection of data arranged in order; 9. Function type, which is a block of code with a specific function.

There are several types in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Data type refers to the type of value that can be stored and manipulated in the program. Each programming language has its supported data types. Different data types are used to store different data, such as Text, values, images, etc.

JavaScript is a dynamically typed language. When defining a variable, you do not need to specify the type of the variable in advance. The type of the variable is dynamically determined by the JavaScript engine during the running of the program. In addition, you can use the same Variables to store different types of data, for example:

var a;  // 此时 a 为 Undefined
a = "http://c.biancheng.net/"; // 此时 a 为 String 类型
a = 123;  // 此时 a 为 Number 类型

Data types in JavaScript can be divided into two types:

  • Basic data types (value types): characters String, Number, Boolean, Null, Undefined, Symbol;

  • Reference data type: Object, array (Array), function (Function).

Tip: Symbol is a new data type introduced in ECMAScript6 that represents a unique value.

1. String type

The string (String) type is a period wrapped in single quotes '' or double quotes "" text, such as '123', "abc". It should be noted that single quotes and double quotes are different ways of defining a string and are not part of the string.

2. Number type

The numerical (Number) type is used to define numerical values. JavaScript does not distinguish between integers and decimals (floating point numbers). Use the Number type uniformly to represent

Note: The number of values ​​that can be defined by the Number type is not unlimited. The Number type in JavaScript can only represent -(2∧53 - 1) to (2∧53 -1) value between.

3. Boolean type

The Boolean type has only two values, true (true) or false (false). When doing Conditional judgment is often used. In addition to directly using true or false to define Boolean type variables, you can also get Boolean type values ​​through some expressions

4. Null type

Null is a special data type with only one value, which represents a "null" value, that is, there is no value, nothing. It is used to define a null object pointer.

Use the typeof operator to check the type of Null. You will find that the type of Null is Object, which means that Null actually uses a special value belonging to Object. So by assigning the variable to Null we create an empty object.

5. Undefined type

Undefined is also a special data type with only one value, which means undefined. When we declare a variable but do not assign a value to the variable, the default value of the variable is Undefined.

6. Symbol type

Symbol is a new data type introduced in ECMAScript6, which represents a unique value.

Symbol value is generated by Symbol function. The attribute name of an object can have two types, one is the original string, and the other is the new Symbol type. Attribute names are of the Symbol type and are unique, ensuring that they will not conflict with other attribute names.

let s1=Symbol()
let s2=Symbol()
console.log(s1)
//Symbol()
console.log(s2)
//Symbol()
console.log(s1===s2)
//false

//Symbol函数能接受字符串作为参数,表示对Symbol实例的描述
let s1=Symbol('xxx')
let s2=Symbol('hhh')
console.log(s1)
//Symbol(xxx)
console.log(s2)
//Symbol(hhh)
console.log(s1===s2)
//false复制代码

Symbol函数前不能使用new命令,会报错。这是因为生成的 Symbol 是一个原始类型的值,不是对象。也就是说,由于 Symbol 值不是对象,所以不能添加属性。相当于是一种特殊的字符串。

应用场景

  • 作为属性名

由于 Symbol 值都是不相等的,这意味着 Symbol 值可以作为标识符,用在对象的属性名,就能保证不会出现同名的属性。这对于一个对象由多个模块构成的情况非常有用,防止某一个键被不小心改写或覆盖。

const grade={
    张三:{address:'qqq',tel:'111'},
    李四:{address:'aaa',tel:'222'},
    李四:{address:'sss',tel:'333'},
}
console.log(grade)
//张三: {address: "qqq", tel: "111"} 李四: {address: "sss", tel: "333"}
//对象的key值不能重复 如果有重复 后面的value值就会覆盖前面的


//使用Symbol解决,相当于一个独一无二的字符串
const stu1=Symbol('李四')
const stu2=Symbol('李四')
console.log(stu1===stu2)
//false
const grade={
    [stu1]:{address:'aaa',tel:'222'},
    [stu2]:{address:'sss',tel:'333'},
}
console.log(grade)
//李四:{address:'sss',tel:'222'} 李四:{address:'sss',tel:'333'}
console.log(grade[stu1])
//李四:{address:'sss',tel:'222'}
console.log(grade[stu2])
//李四:{address:'sss',tel:'333'}
  • 属性遍历

const sym=Symbol('imooc')
class User{
    constructor(name){
        this.name=name
        this[sym]='imooc.com'
    }
    getName(){
        return this.name+this[sym]
    }
}
const user=new User('www')

//for in的方法不能遍历到Symbol属性 像被隐藏了
for(let key in user){
    console.log(key)//name 
}

//Object.keys(obj)方法也不能遍历到Symbol属性
for(let key of Object.keys(user)){
    console.log(key)//name 
}

//Object.getOwnPropertySymbols(obj)只能获取到Symbol属性
for(let key of Object.getOwnPropertySymbols(user)){
    console.log(key)//Symbol(imooc) 
}

//Reflect.ownKeys(obj)对象的属性都能获取到
for(let key of Reflect.ownKeys(user)){
    console.log(key)
    //name 
    //Symbol(imooc) 
}
  • 消除魔术字符串

魔术字符串指的是,在代码中多次出现、与代码形成强耦合的某一个具体的字符串或者数值。风格良好的代码,应该尽量消除魔术字符串,改成一些含义清晰的变量代替。

function getArea(shape) {
    let area = 0
    switch (shape) {
        case 'Triangle':
            area = 1
            break
        case 'Circle':
            area = 2
            break
    }
    return area
}
console.log(getArea('Triangle'))
//Triangle和Circle就是魔术字符串。多次出现,与代码形成了“强耦合”,不利于后面的修改和维护。

const shapeType = {
    triangle: Symbol(),
    circle: Symbol()
}

function getArea(shape) {
    let area = 0
    switch (shape) {
        case shapeType.triangle:
            area = 1
            break
        case shapeType.circle:
            area = 2
            break
    }
    return area
}
console.log(getArea(shapeType.triangle))

7、Object 类型

Object数据类型,称为对象,是一组由键、值组成的无序集合。可以用new操作符后跟要创建的对象类型的名称来创建。也可以用字面量表示法创建。在其中添加不同名(包含空字符串在内的任意字符串)的属性。

1)构造对象

使用 new 运算符调用构造函数,可以构造一个实例对象。具体用法如下:

var objectName = new functionName(args);

参数说明如下:

  • objectName:返回的实例对象。

  • functionName:构造函数,与普通函数基本相同,但是不需要 return 返回值,返回实例对象,在函数内可以使用 this 预先访问。

  • args:实例对象初始化配置参数列表。

示例

下面示例使用不同类型的构造函数定义各种实例。

var o = new Object();  //定义一个空对象

var a = new Array();  //定义一个空数组

var f = new Function();  //定义一个空函数

2)对象直接量

使用直接量可以快速创建对象,也是最高效、最简便的方法。具体用法如下:

var objectName = {
    属性名1 : 属性值1,
    属性名2 : 属性值2,
    ...
    属性名n : 属性值n
};

在对象直接量中,属性名与属性值之间通过冒号进行分隔,属性值可以是任意类型的数据,属性名可以是 JavaScript 标识符,或者是字符串型表达式。属性于属性之间通过逗号进行分隔,最后一个属性末尾不需要逗号。

在 JavaScript 中,对象类型的键都是字符串类型的,值则可以是任意数据类型。要获取对象中的某个值,可以使用对象名.键的形式,如下例所示:

var person = {
    name: 'Bob',
    age: 20,
    tags: ['js', 'web', 'mobile'],
    city: 'Beijing',
    hasCar: true,
    zipcode: null
};
console.log(person.name);       // 输出 Bob
console.log(person.age);        // 输出 20

8、Array 类型

数组(Array)是一组按顺序排列的数据的集合,数组中的每个值都称为元素(Element),每个元素的名称(键)被称为数组下标(Index)。数组的长度是弹性的、可读写的。

数组中可以包含任意类型的数据。

在 JavaScript 中定义(创建或者声明)数组的方法有两种:构造数组和数组直接量。

1)构造数组

使用 new 运算符调用 Array() 类型函数时,可以构造一个新数组。

示例:

  • 直接调用 Array() 函数,不传递参数,可以创建一个空数组。

var a = new Array();  //空数组
  • 传递多个值,可以创建一个实数组。

var a = new Array(1, true, "string", [1,2], {x:1,y:2});  //实数组

每个参数指定一个元素的值,值得类型没有限制。参数的顺序也是数组元素的顺序,数组的 length 属性值等于所传递参数的个数。

  • 传递一个数值参数,可以定义数组的长度,即包含元素的个数。

var a = new Array(5);  //指定长度的数组

参数值等于数组 length 的属性值,每个元素的值默认值为 undefined。

  • 如果传递一个参数,值为 1,则 JavaScript 将定义一个长度为 1 的数组,而不是包含一个元素,其值为 1 的数组。

var a = new Array(1);
console.log(a[0]);

2)数组直接量

数组直接量的语法格式:在中括号中包含多个值列表,值之间用逗号分隔。

下面代码使用数组直接量定义数组。

var a = [];  //空数组
var a = [1, true, "0", [1,0], {x:1,y:0}];  //包含具体元素的数组

推荐使用数组直接量定义数组,因为数组直接量是定义数组最简便、最高效的方法。

9、Function 类型

函数(Function)是一段具有特定功能的代码块,函数并不会自动运行,需要通过函数名调用才能运行,如下例所示:

function sayHello(name){
    return "Hello, " + name;
}
var res = sayHello("Peter");
console.log(res);  // 输出 Hello, Peter

此外,函数还可以存储在变量、对象、数组中,而且函数还可以作为参数传递给其它函数,或则从其它函数返回,如下例所示:

var fun = function(){
    console.log("http://c.biancheng.net/js/");
}
function createGreeting(name){
    return "Hello, " + name;
}
function displayGreeting(greetingFunction, userName){
    return greetingFunction(userName);
}
var result = displayGreeting(createGreeting, "Peter");
console.log(result);  // 输出 Hello, Peter

【推荐学习:javascript高级教程

The above is the detailed content of There are several types in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn