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.
Object:
- 是复合类型,由简单数据类型和复合数据类型组成的。 - 由一对{ }包起来的, - 0对或者多对 键名和键值 组成的对, - 每对键值对 之间用","隔开,最后一个不要加","
Method 1: Through ConstructorCreate object
new Object();
Method 2 : Object literal creates an 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>
Obtaining object values
- 方式一:对象.键名(属性名); - 方式二:对象["键名"];
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:
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!