Home>Article>Web Front-end> Master JavaScript objects in one article

Master JavaScript objects in one article

WBOY
WBOY forward
2022-05-09 17:57:12 1938browse

This article brings you relevant knowledge aboutjavascript, 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, andsymbol) and a complex typeobject(also is the object type).

Compared with primitive data types,

objectis called a complex type because primitive types can only represent one type of data, such asNumberrepresents a number.Stringrepresents strings, etc., whileobjectcan contain all primitive data types in the form ofkey-value pairs.

For example, we can use the

symboltype to represent the object'sID, theStringtype to represent the object's name, and theBooleanindicates the gender of the object, etc. Each type of data in the object is called anattributeof 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 ofJavaScript, but also in all object-oriented languages, such asC,Java,Python,C# are all very important concepts. If you want to learnJavaScriptwell, you must be proficient or even proficient in the characteristics of objects, because objects penetrate all aspects ofJavaScript.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:

let child = { name:'Tom', age:8,}
The above code creates a simple object and assigns the object to the variable

child

. Thechildobject has two attributes (two values), one isname, the other isage.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, wherenameis 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:

let nullObj1 = {}; //创建也给空的对象let nullObj2 = new Object(); //同样创建了一个空对象
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 isobject name.variable name.Give a simple example:

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

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 inchild, you only need to simply usechild.name.

增加属性

在一个对象变量创建完成后,我们还可以随时向变量中添加新的属性,方法如下:

let child = { name:'Tom', age:8,}child.height = 800;//创建了一个新的属性heightconsole.log(child.height);

代码执行结果如下:

向对象变量中添加新的属性,只需要直接使用.属性名,然后直接向新属性赋值即可。

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

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

更改属性

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

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

代码执行结果如下:

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

删除属性

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

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

代码执行结果如下:

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

多单词键值

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

举个例子:

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

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

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

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

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

方括号

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

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

代码执行结果如下:

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

例如:

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

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

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

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

举个栗子:

let child = { prop1:0, prop2:1, prop3:2,}let prop = 'prop';for(let i=1;i

在这里,范围属性值的key是通过计算得到的,这一功能用.是不能实现的。

计算属性

在创建对象时,我们还可以通过变量指定对象的键名,此类属性叫做计算属性

举个例子:

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

代码执行结果如下:

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

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

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

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

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

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

代码执行结果如下:

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

属性简写

在实际应用中,或者匿名对象中,我们常常会使用和变量同名的属性,举个例子:

let name = 'Tom';let age = 8;let child = { name:name, //属性名和变量名一样,都是name age:age,};

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

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

代码的执行结果:

> let name = 'Tom'; let age = 8; let child = { name, age, } child

属性命名

和变量命名不同,我们几乎可以使用任何值作为属性的名称,包括关键字和数字:

关键字作为变量名

虽然听起来不可思议,实际上,所有的关键字都可以作为对象的属性名:

let obj = { for:0, while:1, function:2, alert:3,}

代码执行结果:

> let obj = { for:0, while:1, function:2, alert:3, } obj

数字作为关键字

数字也可以作为关键字的名称,如下:

let obj = { 0:'Number',//隐式转换为"0" 1:'Number',}console.log(obj['0']);

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

属性名称中的陷阱

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

举个例子:

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

in 操作符

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

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

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

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

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

代码执行结果:

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

虽然prop是存在的,但是以上案例并不能正确的返回结果。

这个时候就需要使用in

let obj = { prop:undefined,};if('prop' in obj){ console.log('yes');}else{ console.log('no');}

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

> let obj = { prop:undefined, }; if('prop' in obj){ console.log('yes'); }else{ console.log('no'); }

属性遍历

如果我们不知道对象中都存在什么属性,如何取得所有的属性值呢?
这时候就需要使用for .. in ..语句了,它类似于for循环,但是更简洁。

语法

for (key in obj){ ...}

举个简单的小李子:

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

代码执行结果如下:

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

属性顺序

当我们创建一个对象并遍历其中所有的属性时,属性是如何排列的呢?答案是:特别的顺序排列,并遵循以下规则:

  1. 数字属性以数字顺序排列;
  2. 其他属性按照创建顺序排列;
  3. 数字属性在其他属性之前;

举个例子:

let obj = { name:'Tom', age:99, 7:'7', 1:'1', 9:'9',}for (let key in obj){ console.log(key+':'+obj[key]);}

代码执行结果:

> let obj = { name:'Tom', age:99, 7:'7', 1:'1', 9:'9', } for (let key in obj){ console.log(key+':'+obj[key]); }

【相关推荐:javascript视频教程web前端

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete