Home > Web Front-end > JS Tutorial > body text

Master JavaScript objects in one article

WBOY
Release: 2022-05-09 17:57:12
forward
1990 people have browsed it

This article brings you relevant knowledge about javascript, which mainly introduces issues related to objects, including object-oriented, object operations, property naming, etc. Let’s talk about it together Take a look, hope it helps everyone.

Master JavaScript objects in one article

[Related recommendations: javascript video tutorial, web front-end

JavaScript Object# Eight data types of

##JavaScript, including seven primitive data types (Number, BigInt, String , Boolean, null, undefined, and symbol) and a complex type object (also is the object type).

Compared with primitive data types,

object is called a complex type because primitive types can only represent one type of data, such as Number represents a number. String represents strings, etc., while object can contain all primitive data types in the form of key-value pairs.

For example, we can use the

symbol type to represent the object's ID, the String type to represent the object's name, and the Boolean indicates the gender of the object, etc. Each type of data in the object is called an attribute of the object. An object can theoretically have countless attributes, which are unified in a pair of curly braces{...}# Created in ##.

Object-oriented

is not only a language feature of JavaScript, but also in all object-oriented languages, such as C , Java , Python, C# are all very important concepts. If you want to learn JavaScript well, you must be proficient or even proficient in the characteristics of objects, because objects penetrate all aspects of JavaScript. Object-oriented VS process-oriented

Object-oriented is a programming idea, not a new technology. Before object-oriented was born, programmers organized large amounts of code with process-oriented thinking.

What is object-oriented? This question is often asked in schools and interviews. We can understand the answer very profoundly:

Everything is an object

. Although this is absolutely correct, it is not the answer that the interviewer or teacher wants. Object-oriented is a programming idea, a way of organizing code, which is relative to

Process-oriented

. In process-oriented, the programmer is God, and God directs and directs everything. For example, we often give an example: putting an elephant in the refrigerator. In the process of facing God, you need to open the refrigerator door first, then put the elephant into the refrigerator, and finally close the refrigerator door. All processes are operated by God alone. In object-oriented, the refrigerator and the elephant are both existing objects, and the refrigerator will open the door by itself, the elephant will enter the refrigerator by itself, and then the refrigerator will close the door by itself. The whole process is coordinated by God, but the specific process of doing things is completed by the subject himself, such as how to open the refrigerator door, how to enter the refrigerator, etc.

Syntax

You don’t need to use keywords to define an object. You can create an object by wrapping the key-value pair in curly braces

{..}

. The syntax is as follows: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">let child = { name:'Tom', age:8,}</pre><div class="contentsignin">Copy after login</div></div>The above code creates a simple object and assigns the object to the variable

child

. The child object has two attributes (two values), one is name, the other is age. The so-called key-value pair (key:value
) is a simple mapping between names and values. For example, name:'Tom'
in the above example is a key-value pair, where name is the key and "Tom" is the corresponding value. In actual use, the corresponding value can be obtained through the key, just like using the variable name to obtain the variable value. Empty object

If an object does not have any attributes, then the object is an empty object. We can obtain an empty object by simply assigning

{}

to a variable, or we can use another method: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">let nullObj1 = {}; //创建也给空的对象let nullObj2 = new Object(); //同样创建了一个空对象</pre><div class="contentsignin">Copy after login</div></div>Object operation

After an object is created, It is not static. When we use the object, we can query the properties of the object or change the object at any time.

Query attributes

To query the attribute value of an object, you need to use a new symbol:

.

, and the syntax is object name.variable name. Give a simple example:

let child = {
	name:'Tom',
	age:8,};console.log(child.name);console.log(child.age)
Copy after login

The code execution result is as follows:

Master JavaScript objects in one articleIn the above case, if we want to view the variables For the

name

attribute in child, you only need to simply use child.name. <h3>增加属性</h3> <p>在一个对象变量创建完成后,我们还可以随时向变量中添加新的属性,方法如下:</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">let child = { name:'Tom', age:8,}child.height = 800;//创建了一个新的属性heightconsole.log(child.height);</pre><div class="contentsignin">Copy after login</div></div> <p>代码执行结果如下:<br><img src="https://img.php.cn/upload/article/000/000/067/fe2059ee460429c7555eaf109d8f6ba7-1.png" alt=""></p> <p>向对象变量中添加新的属性,只需要直接使用<code>.属性名,然后直接向新属性赋值即可。

如果我们此时查看变量child的内容,可以发现height属性已经位列其中了:

对象的属性类型可以是任意的,我们可以直接使用child.isBoy=true向对象中添加布尔值,或者使用child.money=null添加一个值为空的属性。

更改属性

JavaScript对象更改属性值也非常简单,直接向变量赋值就可以了,举个简单的小李子:

let child={
	name:'Tom',
	age:8,}child.age=12;console.log(child);
Copy after login

代码执行结果如下:

可以看到,age变量已经从8变成了12

删除属性

对象删除属性需要使用一个新的关键字delete,使用delet 对象名.属性名删除对象的属性:

let child = {
	name:'Tom',
	age:8,}delete child.age;console.log(child);
Copy after login

代码执行结果如下:

从代码的执行结果可以看到属性age已经被删掉了。

多单词键值

对象的属性名(键)还能够使用空格隔开的多个单词,不过在创建此类属性时需要使用双引号把键名包裹起来。

举个例子:

let child={
	name = 'Tom',
	age:8,
	"favorite cat":'Jerry',}
Copy after login

以上代码就创建了一个键名为"favorite cat"的键值对,但是在访问属性值的时候,如果使用:

child.favorite cat = 'Bob'; //语法错误
Copy after login

这种方式是错误的,引擎会把favorite当作一个键名,并在遇到cat时报错。

访问此类键值,就需要方括号

方括号

.可以访问普通的属性名,在例如"favorite cat"之类的变量时可以使用[],举个例子:

let child={
	name:'Tom',
	age:8,
	"favorite cat":'Jerry',}console.log(child['favorite cat']);
Copy after login

代码执行结果如下:

方括号提供了.之外的属性访问方式,我们完全可以通过方括号代替.来操作对象的属性。

例如:

let child = {
	name:'Tom',
	age:8,}child['favorite cat']='Jerry';	
	//增加属性child['name']='Bob';			
	//修改属性delete child['age'];			
	//删除数console.log(child['name']);		
	//查看属性
Copy after login

除了常规的属性操作之外,方括号还能通过变量访问对象属性:

let child = {
	name:'Tom',
	age:8,}let prop = 'name';console.log(child[prop]);prop='age';console.log(child[prop]);
Copy after login

通过变量访问属性值的能力为我们提供了非常有用的变量访问方式,例如我们可以在程序中计算出属性的键名,然后再通过键名访问键值。

举个栗子:

let child = {
	prop1:0,
	prop2:1,
	prop3:2,}let prop = 'prop';for(let i=1;i<p>在这里,范围属性值的<code>key</code>是通过计算得到的,这一功能用<code>.</code>是不能实现的。</p><h2>计算属性</h2><p>在创建对象时,我们还可以通过变量指定对象的键名,此类属性叫做<strong>计算属性</strong>。</p><p>举个例子:</p><pre class="brush:php;toolbar:false">let propName = 'name';let child ={
	[propName]:'Tom',
	age:8,}
Copy after login

代码执行结果如下:

> let propName = 'name';
> let child ={
 	[propName]:'Tom',
 	age:8,
> }
> undefined
> child
> {name: 'Tom', age: 8}
Copy after login

上例中的[propName]就是一个计算属性,意义也非常简单,就是使用变量propName中存储的值(此处为"name")作为对象的键名。

以上的代码本质上和下面的代码作用相同:

let propName='name';let child = {
	age:8,}child[propName]='Tom';
Copy after login

方括号中还可以使用复杂的表达式:

let child = {['prop' + 2 * 3]:'Tom',}
Copy after login

代码执行结果如下:

> let child = {
	['prop'+2*3]:'Tom',
  } child<h2>属性简写</h2><p>在实际应用中,或者匿名对象中,我们常常会使用和变量同名的属性,举个例子:</p><pre class="brush:php;toolbar:false">let name = 'Tom';let age = 8;let child = {
	name:name,	//属性名和变量名一样,都是name
	age:age,};
Copy after login

这种情况下,我们就可以简写对象属性,如下:

let name = 'Tom';let age = 8;let child = {
	name, // 等同于name:name;
	age,}
Copy after login

代码的执行结果:

> let name = 'Tom';
  let age = 8;
  let child = {
		name,
		age,
  } child<h2>属性命名</h2><p>和变量命名不同,我们几乎可以使用任何值作为属性的名称,包括关键字和数字:</p><h3>关键字作为变量名</h3><p>虽然听起来不可思议,实际上,所有的关键字都可以作为对象的属性名:</p><pre class="brush:php;toolbar:false">let obj = {
	for:0,
	while:1,
	function:2,
	alert:3,}
Copy after login

代码执行结果:

> let obj = {
  	for:0,
  	while:1,
  	function:2,
  	alert:3,
  } obj<h3>数字作为关键字</h3><p>数字也可以作为关键字的名称,如下:</p><pre class="brush:php;toolbar:false">let obj = {
	0:'Number',//隐式转换为"0"
	1:'Number',}console.log(obj['0']);
Copy after login

数字作为属性名称时,会被隐式转换为字符串,在访问属性时,不能使用.,必须使用方括号代替。

属性名称中的陷阱

在命名中,有一个小陷阱,我们不能使用__proto__作为属性的名称,这个属性是对象的一个特殊,后继会特别介绍。

举个例子:

let obj = {};obj.__proto__ = 1;console.log(obj.__proto__);
Copy after login

in 操作符

JavaScript有一个需要注意的特性,即使访问一个不存的属性时也不会报错,仅仅是返回undefined
那我们如何知道,属性是否存在于对象之中呢?

最简单的方式是使用if语句:

let obj = {};if(obj.someProp === undefined){
	...}
Copy after login

这么做在大部分情况下是没有问题的,但是当属性名称的值就是undefined本身时,就会出现错误:

let obj = {
	prop : undefined}obj.prop === undefined ? console.log('no'):console.log('yes');
Copy after login

代码执行结果:

> let obj = {
  	prop : undefined
  }
  obj.prop === undefined ? console.log('no'):console.log('yes');
  no<p>虽然<code>prop</code>是存在的,但是以上案例并不能正确的返回结果。</p><p>这个时候就需要使用<code>in</code></p><pre class="brush:php;toolbar:false">let obj = {
	prop:undefined,};if('prop' in obj){
	console.log('yes');}else{
	console.log('no');}
Copy after login

这么做是不是优雅了许多呢?

> let obj = {
  	prop:undefined,
  };
  if('prop' in obj){
  	console.log('yes');
  }else{
  	console.log('no');
  }<h2>属性遍历</h2><p>如果我们不知道对象中都存在什么属性,如何取得所有的属性值呢?<br> 这时候就需要使用<code>for .. in ..</code>语句了,它类似于<code>for</code>循环,但是更简洁。</p><p><strong>语法</strong></p><pre class="brush:php;toolbar:false">for (key in obj){
	...}
Copy after login

举个简单的小李子:

let child = {
	name:'Tom',
	age:8,
	height:180,}for (let key in child){
	console.log(key+':'+child[key]);}
Copy after login

代码执行结果如下:

> let child = {
  	name:'Tom',
  	age:8,
  	height:180,
  }

  for (let key in child){
  	console.log(key+':'+child[key]);
  }<h2>属性顺序</h2><p>当我们创建一个对象并遍历其中所有的属性时,属性是如何排列的呢?答案是:特别的顺序排列,并遵循以下规则:</p><ol>
<li>数字属性以数字顺序排列;</li>
<li>其他属性按照创建顺序排列;</li>
<li>数字属性在其他属性之前;</li>
</ol><p>举个例子:</p><pre class="brush:php;toolbar:false">let obj = {
	name:'Tom',
	age:99,
	7:'7',
	1:'1',
	9:'9',}for (let key in obj){
	console.log(key+':'+obj[key]);}
Copy after login

代码执行结果:

> let obj = {
  	name:'Tom',
  	age:99,
  	7:'7',
  	1:'1',
  	9:'9',
  }
  for (let key in obj){
  	console.log(key+':'+obj[key]);
  }<p>【相关推荐:<a href="https://www.php.cn/course/list/17.html" target="_blank" textvalue="javascript视频教程">javascript视频教程</a>、<a href="https://www.php.cn/course/list/1.html" target="_blank">web前端</a>】</p>
Copy after login

The above is the detailed content of Master JavaScript objects in one article. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template