Home  >  Article  >  Web Front-end  >  Use of JS objects

Use of JS objects

php中世界最好的语言
php中世界最好的语言Original
2018-05-24 14:14:481360browse

This time I will bring you the use of JS objects. What are the precautions when using JS objects. The following is a practical case, let’s take a look.

1. Definition of object

Object:

    - 是复合类型,由简单数据类型和复合数据类型组成的。
    - 由一对{ }包起来的,
    - 0对或者多对 键名和键值 组成的对,
    - 每对键值对 之间用","隔开,最后一个不要加","

2. Creation of object

Method 1: Through ConstructorCreate object

  • new Object();

Method 2 : Object literal creates an object

  • { };

3. Add or modify attributes for the object

Method 1: Pass"."

<script>
    //通过构造函数创建对象
    var obj= new Object();
    //为对象添加属性
    obj.a=2;
    console.log(obj);//{a: 1}
    
    //通过对象字面量创建对象
    var t={};
    //为对象添加属性
    t.a=2;
    console.log(t);//{a: 1}    
</script>

Method 2:"[ ]"

<script>
    //通过构造函数创建对象
    var obj= new Object();
    //为对象添加属性
    obj.["a"]=2;
    console.log(obj);//{a: 1}
    
    //通过对象字面量创建对象
    var t={};
    //为对象添加属性
    t.["a"]=2;
    console.log(t);//{a: 1}    
</script>

Method 3: Write directly inside

<script>
    var obj= {
            name: "k",
            age: 12,
            gender: "male"
        }
     console.log(obj);//{name: "k", age: 12, gender: "male"}
</script>

4. Obtaining attribute values

Obtaining object values

- 方式一:对象.键名(属性名);
- 方式二:对象["键名"];

5.Using in and for in

Use of in:

  属性名 in 对象名
      检测 在 对象中 是否 含有此属性名。

eg:

<script>
    var obj={
        name:"L";
        age:22;
    };
    console.log(age in obj);//true
    console.log(gender in obj);//false
</script>

Use of for in:

Traversal All properties within object feel like a cycle.

<script>
        var obj={
                name:"k",
                age:21,
                gender:"women"
        };
        // i是指对象的属性名,会遍历对象的属性值。
        for (var i in obj){
            console.log("第"+i+"项的属性值为:"+obj[i]);
        }
        var attr=[1,2,3,4];
        for (var i in attr){
            console.log("第"+i+"项值为:"+attr[i]);
        }
</script>

The screenshot of the result is:
Use of JS objects

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Detailed explanation of the implementation steps of PromiseA

Detailed explanation of the steps to highlight the selected li in react implementation

The above is the detailed content of Use of JS objects. 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