举例讲解JavaScript中关于对象操作的相关知识_基础知识
从数组到对象
var myarr = ['red','blue','yellow','purple']; myarr;// ["red","blue","yellow","purple"] myarr[0];//"red" myarr[3];//"purple'
数组大家都很熟悉吧,我们可以理解为一个Key对应一个Value,而这个Key在数组中,已经默认了(如上述代码,它的key分别是0,1,2,3 value是red,blue,yellow,purple)。
那么一个对象就可以理解为一个自定义Key的数组。看如下代码
var hero ={ breed: 'Turtle', occupation:'Ninja' };
上述代码我们可以了解到:
1.对象的名称叫hero.
2.和数组不同的是用符号'{'替代了'['
3.对象的属性(如breed和occupation)用符号','分隔
4.Key和Value的语法是 KEY:VALUE
还有需要注意到是不管属性(也就是key)是放在双引号,单引号,或者是没有引号,他们的结果都是一样的,下面的代码是一样的
var obj={a:1,b:2}; var obj={'a':1,'b':2}; var obj={"a":1,"b":2};
推荐的写法是不要把属性放在引号中。除非属性的名称是特殊符号,如数字,或者带有空格等等。
本篇很简单,要注意的是,定义数组的符号[] ,而定义对象的符号为{}
元素,属性,方法
学习数组的时候,我们可以说数组里包含了元素,当谈到对象的时候,我们可以改变下说法
var animal={ name: 'dog', run:function(){ alert("running"); } }
name就是属性(property),run本身是个函数,在这个对象中,我们叫方法(method)。
访问对象的属性
有两种方式访问对象的属性。
用数组的形式如:animal['name']
用点的方式访问:animal.name
第一种访问方法适合任意情况。但是如果属性是无效的命名的话,如上一节所说的属性命名'1name'或者'my name'这种情况用点的方式访问就是错误的。这一点要注意。
下面具体看一个对象访问的例子
var book = { name:'Javascript Fundation', published:jixie. author:{ firstname:'nicholas', lastname:'xia' } };
1.获取author对象的firstname属性
book.author.firstname //nicholas
2.获取author对象的lastname属性,我们尝试用另一个写法
book['author']['lastname'] //xia
我们也可以用混合的访问方式
book.author['lastname']或者book['author'].lastname 这些方式都是有效的,要灵活去运用
在属性是动态的情况下,一般用数组的访问对象的方法。
var key ='lastname' book.author[key];//xia
调用对象的方法
var hero = { breed: 'Turtle', occupation: 'Ninja', say: function() { return 'I am ' + hero.occupation; } } hero.say();
访问对象的方法很简单,有点就行,不过也可以用数组的方式,看起来比较诡异
如 hero['say']();
不推荐这种写法,访问对象的时候尽量用点的方式。
修改属性和方法
因为Javascript是动态语言,所以在任何时候都可以修改对象的属性和方法。看如下的例子
var hero={};
hero是个空的对象。
typeof hero.breed;//undefined
说明了hero对象没有breed的属性
接下来可以添加属性和方法了
hero.breed = 'turtle'; hero.name = 'Leonardo'; hero.sayName = function() {return hero.name;};
调用方法
hero.sayName();//Leonardo
删除属性
delete hero.name;//true hero.sayName();//方法失败
This
var hero = { name : 'Rafaelo', sayName : function(){ return this.name; } } hero.sayName();//Rafaelo
this的意思就是这个对象的意思,关于this的复杂问题以后在讨论。
构造函数(Constructor Functions)
另一种创建对象的方式是用构造函数,直接看例子
function Hero(){ this.name ='Refaelo'; } var hero = new Hero(); hero.name;//Refaelo
这种方式的好处在于创建个对象的时候可以传入参数
function Hero(name){ this.name = name; this.whoAreYou = function(){ return this.name; } } var hi = new Hero('nicholas'); hi.whoAreYou();//nicholas
要注意的时候,不要丢点 new 操作符。。。
全局对象
上几节我们说过全局变量的事情,已经说过了我们要尽量避免使用全局变量,当我们学过对象的时候,我们在看看全局变量究竟怎么回事,其实全局变量就是全局对象一个属性了。如果主机的环境是web浏览器,全局变量就是window。
如果我们定义 var a = 1;
我们可以这么理解:
一个全局变量a,
做为window的一个属性a.我们可以这么调用window.a或者window['a']
再看看预定义函数的parseInt('123 m');我们可以写为window.parseInt('123 m');
constructor 属性
对象建立之后,后台有创建了个隐藏属性,constructor.
h2.constructor;//Hero(name)
因为constructor的属性是对函数的引用。如果你不关心h2对象是由什么创建的,而只关心创建一个新的对象和h2相似就用如下写法
var h3 = h2.constructor('Nicholas'); h3.name ;//Nicholas
我们来看看如下写法的意思
var o = {}; o.constructor;//Object() typeof o.constructor;//"functions"
其实就是隐藏了 new Object() ,更深的层次应用以后几个教程在说明。
instanceof 操作符
用instanceof来判断对象是否是指定的构造函数创建的。
function Hero(){ } var h = new Hero(); var o = {}; h instanceof Hero;//true h instanceof Object;//false o instanceof Object;//true
要注意的是instanceof 后面的是个引用 不是个函数 如错误写法 h instanceof Hero();//错误
函数返回对象
可以用构造函数来创建个对象,也可以通过普通函数返回对象来创建对象
function factory(name){ return { name:name }; }
用这个方法创建对象
var o = factory('one'); o.name
让我们接下来看看比较少见的构造函数返回对象的例子
function C(){ this.a = 1; return {b:2}; } var c2 = new C(); typeof c2.a //undefined c2.b; // 2
说明了 并不返回this了 而是返回了对象{b:2}。。这点要注意
传递对象
如果传递一个对象到函数里,那么传递的是个引用。如果改变了这个引用,也就会改变原始的对象。
下面是个对象赋值的例子
var original = {name:'nicholas'}; var copy =original; copy.name;//'nicholas'; copy.name = 'Jason'; original.name;// 'Jason';
修改了copy的属性name 也就等于修改了original的属性name
对象传参到函数中,也是同样的。
function modify(o){ o.name ='Jason' } var original={name:'nicholas'}; modify(original); original.name;//Jason
对象的比较
两个对象的比较如果是true的话,那么他们就是同一个对象的引用。
var fido ={breed:'dog'}; var benji ={breed:'dog'}; benji===fido; //false; benji==fido; //false;
以上的代码都不是同一引用,所以都是false

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

The Request object in PHP is an object used to handle HTTP requests sent by the client to the server. Through the Request object, we can obtain the client's request information, such as request method, request header information, request parameters, etc., so as to process and respond to the request. In PHP, you can use global variables such as $_REQUEST, $_GET, $_POST, etc. to obtain requested information, but these variables are not objects, but arrays. In order to process request information more flexibly and conveniently, you can

In PHP, an array is an ordered sequence, and elements are accessed by index; an object is an entity with properties and methods, created through the new keyword. Array access is via index, object access is via properties/methods. Array values are passed and object references are passed.

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.
