亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Declaration method
Symbol.for() Global definition of Symbol
Symbol.keyFor()
Application scenario
As an attribute name
Attribute traversal%%PRE_BLOCK_4%%
Eliminate magic string
Home Web Front-end JS Tutorial A brief analysis of javascript data type learning Symbol type

A brief analysis of javascript data type learning Symbol type

Mar 18, 2022 am 11:01 AM
es6 javascript symbol type type of data

This article will take you through the new data type of ES6: Symbol, and talk about the declaration and usage of the Symbol type. I hope it will be helpful to everyone!

A brief analysis of javascript data type learning Symbol type

Symbol is a new primitive data type that represents uniqueness. It is the seventh data type in JavaScript. The other six are: undefined, null, String, Number, Object

Declaration method

Symbol value is generated through the 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. [Related recommendations: javascript learning tutorial]

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

//Symbol函數(shù)能接受字符串作為參數(shù),表示對Symbol實例的描述
let?s1=Symbol('xxx')
let?s2=Symbol('hhh')
console.log(s1)
//Symbol(xxx)
console.log(s2)
//Symbol(hhh)
console.log(s1===s2)
//false復制代碼

You cannot use the new command before the Symbol function, and an error will be reported. This is because the generated Symbol is a primitive type value, not an object. That is, since Symbol values ??are not objects, properties cannot be added. Equivalent to a special string.

Symbol.for() Global definition of Symbol

Symbol.for() accepts a string as a parameter, and then searches for whether the parameter is used as a name Symbol value. If there is, return this Symbol value, otherwise create a new Symbol value named with this string and register it globally.

let s1 = Symbol.for('xxx')
let s2 = Symbol.for('xxx')
console.log(s1 === s2) // true


function foo(){
    return Symbol.for('hello')
}
const x=foo()
const y=Symbol.for('hello')
console.log(x === y)//true

The two writing methods of Symbol.for() and Symbol() will generate new Symbol. The difference is that the former will be registered in the global environment for search, while the latter will not. Symbol.for() will not return a new Symbol type value every time it is called. Instead, it will first check whether the given key already exists, and then create a new value if it does not exist.

Symbol.keyFor()

The Symbol.keyFor() method returns a registered Symbol type value key.

const s1 = Symbol('foo')
console.log(Symbol.keyFor(s1)) // undefined

const s2 = Symbol.for('foo')
console.log(Symbol.keyFor(s2)) // foo

Application scenario

As an attribute name

Since the Symbol values ??are not equal, this means ## The #Symbol value can be used as an identifier and used in the object's attribute name to ensure that attributes with the same name will not appear. This is useful when an object is composed of multiple modules, to prevent a key from being accidentally overwritten or overwritten.

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'}

Attribute traversal
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) 
}

Eliminate magic string

Magic string refers to, multiple times in the code A specific string or value that appears and forms

strong coupling with the code. Code with good style should try to eliminate magic strings and replace them with variables with clear meanings.

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就是魔術(shù)字符串。多次出現(xiàn),與代碼形成了“強耦合”,不利于后面的修改和維護。

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))
I am a front-end novice. If there is any wrong content in the article, please give me some advice and discussion!

[Related video tutorial recommendations:

web front-end]

The above is the detailed content of A brief analysis of javascript data type learning Symbol type. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
What data type should be used for gender field in MySQL database? What data type should be used for gender field in MySQL database? Mar 14, 2024 pm 01:21 PM

In a MySQL database, gender fields can usually be stored using the ENUM type. ENUM is an enumeration type that allows us to select one as the value of a field from a set of predefined values. ENUM is a good choice when representing a fixed and limited option like gender. Let's look at a specific code example: Suppose we have a table called "users" that contains user information, including gender. Now we want to create a field for gender, we can design the table structure like this: CRE

What is the best data type for gender fields in MySQL? What is the best data type for gender fields in MySQL? Mar 15, 2024 am 10:24 AM

In MySQL, the most suitable data type for gender fields is the ENUM enumeration type. The ENUM enumeration type is a data type that allows the definition of a set of possible values. The gender field is suitable for using the ENUM type because gender usually only has two values, namely male and female. Next, I will use specific code examples to show how to create a gender field in MySQL and use the ENUM enumeration type to store gender information. The following are the steps: First, create a table named users in MySQL, including

Mind map of Python syntax: in-depth understanding of code structure Mind map of Python syntax: in-depth understanding of code structure Feb 21, 2024 am 09:00 AM

Python is widely used in a wide range of fields with its simple and easy-to-read syntax. It is crucial to master the basic structure of Python syntax, both to improve programming efficiency and to gain a deep understanding of how the code works. To this end, this article provides a comprehensive mind map detailing various aspects of Python syntax. Variables and Data Types Variables are containers used to store data in Python. The mind map shows common Python data types, including integers, floating point numbers, strings, Boolean values, and lists. Each data type has its own characteristics and operation methods. Operators Operators are used to perform various operations on data types. The mind map covers the different operator types in Python, such as arithmetic operators, ratio

Detailed explanation of how to use Boolean type in MySQL Detailed explanation of how to use Boolean type in MySQL Mar 15, 2024 am 11:45 AM

Detailed explanation of how to use Boolean types in MySQL MySQL is a commonly used relational database management system. In practical applications, it is often necessary to use Boolean types to represent logical true and false values. There are two representation methods of Boolean type in MySQL: TINYINT(1) and BOOL. This article will introduce in detail the use of Boolean types in MySQL, including the definition, assignment, query and modification of Boolean types, and explain it with specific code examples. 1. The Boolean type is defined in MySQL and can be

What is the best data type choice for gender field in MySQL? What is the best data type choice for gender field in MySQL? Mar 14, 2024 pm 01:24 PM

When designing database tables, choosing the appropriate data type is very important for performance optimization and data storage efficiency. In the MySQL database, there is really no so-called best choice for the data type to store the gender field, because the gender field generally only has two values: male or female. But for efficiency and space saving, we can choose a suitable data type to store the gender field. In MySQL, the most commonly used data type to store gender fields is the enumeration type. An enumeration type is a data type that can limit the value of a field to a limited set.

Revealing the classification of basic data types in mainstream programming languages Revealing the classification of basic data types in mainstream programming languages Feb 18, 2024 pm 10:34 PM

Title: Basic Data Types Revealed: Understand the Classifications in Mainstream Programming Languages ??Text: In various programming languages, data types are a very important concept, which defines the different types of data that can be used in programs. For programmers, understanding the basic data types in mainstream programming languages ??is the first step in building a solid programming foundation. Currently, most major programming languages ??support some basic data types, which may vary between languages, but the main concepts are similar. These basic data types are usually divided into several categories, including integers

Introduction to basic syntax and data types of C language Introduction to basic syntax and data types of C language Mar 18, 2024 pm 04:03 PM

C language is a widely used computer programming language that is efficient, flexible and powerful. To be proficient in programming in C language, you first need to understand its basic syntax and data types. This article will introduce the basic syntax and data types of C language and give examples. 1. Basic syntax 1.1 Comments In C language, comments can be used to explain the code to facilitate understanding and maintenance. Comments can be divided into single-line comments and multi-line comments. //This is a single-line comment/*This is a multi-line comment*/1.2 Keyword C language

What are the two categories of java data types? What are the two categories of java data types? Jan 26, 2024 pm 03:50 PM

Divided into basic data types and reference data types. Detailed introduction: 1. Basic data types include integer types, floating point types, character types, and Boolean types; 2. Reference data types include classes, interfaces, arrays, enumerations, and other reference types. In Java, primitive data types are passed by value, while reference data types are passed by reference. Basic data types directly store actual values, while reference data types store references (addresses) to objects.

See all articles