Table of Contents
3.3.1 本地对象
Home Web Front-end JS Tutorial Type of object: local object (1)_Basic knowledge

Type of object: local object (1)_Basic knowledge

May 16, 2016 pm 07:22 PM

在ECMAScript中,所有对象并非同等创建的。一般说来,可以创建并使用的对象有三种。

3.3.1 本地对象

ECMA-262把本地对象(native object)定义为“独立于宿主环境的ECMAScript实现提供的对象”。简单说来,本地对象就是ECMA-262定义的类(引用类型)。它们包括:
你已经从上一章了解了一些本地对象(Object、Function、String、Boolean和Number),本书后面的章节中还会讨论一些本地对象。现在要讨论的两种重要的本地对象是Array和Date。
1. Array
与Java不同的是,在ECMAScript中有真正的Array类。可以如下创建Array对象:
如果预先知道数组中项的个数,可以用参数传递数组的大小:
使用这两个方法,一点要使用括号,与它们在Java中的用法相似:
这里创建了一个数组,并定义了三个数组项,即"red"、"green"和"blue"。每增加一个数组项,数组的大小就动态地增长。
此外,如果知道数组应该存放的值,还可用参数声明这些值,创建大小与参数个数相等的Array对象。例如,下面的代码将创建一个有三个字符串的数组:
与字符串类似,数组中的第一个项位于位置0,第二个项位于位置1,依此类推。可通过使用方括号中放置要读取的项的位置来访问特定的项。例如,要用刚才定义的数组输出字符串"green",可以采用下面的代码:
可用属性length得到数组的大小。与字符串的length属性一样,数组的length属性也是最后一个项的位置加1,意味着具有三个项的数组中的项的位置是从0到2。
前面提过,数组可以根据需要增大或减小。因此,如果要为前面定义的数组增加一项,只需把要存放的值放入下一个未使用的位置即可:
在这段代码中,下一个未使用的位置是3,所以值"purple"将被赋予它。增加一项使数组的大小从3变成了4。但如果把值放在这个数组的位置25处会怎样呢?ECMAScript将把从3开始到24的所有位置都填上值null,然后在位置25处放上正确的值,并把数组大小增大为26:
数组最多可以存放4294967295项,这应该可满足大多数程序设计的需要。如果要添加更多的项,则会发生异常。
还可以用字面量表示定义Array对象,即使用方括号([和]),用逗号分隔值。例如,可以用下面的形式重写前面的例子:
注意,在这个例子中,未明确使用Array类。方括号暗示把其中的值存放在Array对象中。用这种方式声明的数组与用传统方式声明的数组相同。
Array对象覆盖了toString()方法和valueOf()方法,返回特殊的字符串。该字符串是通过对每项调用toString()方法,然后用逗号把它们连接在一起构成的。例如,对具有项"red"、"green"和"blue"的数组调用toString()方法或valueOf()方法,返回的是字符串"red,green,blue"。
类似的,toLocaleString()方法返回的也是由数组项构成的字符串。唯一的区别是得到的值是通过调用每个数组项的toLocaleString()方法得到的。许多情况下,该方法返回的值都与toString()方法返回的值相同,也是用逗号连接字符串。
由于开发者也可能希望在数组之外创建这样的值,所以ECMAScript提供了方法join(),它唯一的用途就是连接字符串值。join()方法只有一个参数,即数组项之间使用的字符串。考虑下面的例子:
여기에서는 Join() 메서드를 사용하여 세 가지 다른 배열 표현이 생성됩니다. 첫 번째 Join() 메서드는 쉼표를 사용합니다. 이는 toString() 메서드 또는 valueOf() 메서드를 호출하는 것과 본질적으로 동일합니다. 두 번째와 세 번째 Join() 메서드는 서로 다른 문자열을 사용하여 배열 항목 사이에 이상한 구분 기호를 만듭니다(아마도 별로 유용하지 않음). 이해해야 할 중요한 점은 모든 문자열을 구분 기호로 사용할 수 있다는 것입니다.
이쯤 되면 Array에도 자신을 문자열로 변환하는 메소드가 있는데, String에도 자신을 배열로 변환하는 메소드가 있는 걸까? 대답은 '예'입니다. 이를 위해 String 클래스의 Split() 메소드가 사용됩니다. Split() 메소드에는 매개변수가 하나만 있습니다. 일부 독자들이 짐작할 수 있듯이 이 매개변수는 배열 항목 사이의 구분자로 간주되는 문자열입니다. 따라서 쉼표로 구분된 문자열이 있는 경우 다음 코드를 사용하여 이를 Array 객체로 변환할 수 있습니다.
빈 문자열이 구분 기호로 선언된 경우 분할() 메서드에서 반환된 배열의 각 항목은 문자열의 문자입니다. 예:
여기서 문자열 "green"은 문자열 배열 "g", "r", "e", "e" 및 "n"으로 변환됩니다. 이 기능은 문자열을 문자별로 구문 분석해야 하는 경우 유용합니다.
Array 객체에는 String 클래스와 마찬가지로 concat() 및 Slice() 메소드라는 두 가지 메소드가 있습니다. concat() 메서드는 문자열과 거의 동일한 방식으로 배열과 함께 작동합니다. 매개변수는 배열 끝에 추가되며 반환된 함수 값은 새 Array 객체입니다(원래 배열의 항목과 새 항목 포함). 예:
이 예에서는 concat() 메서드를 사용하여 "yellow" 및 "purple" 문자열을 배열에 추가합니다. aColors2 배열에는 5개의 값이 포함되어 있지만 원래 배열 aColors에는 여전히 3개의 값만 포함되어 있습니다. 이는 두 배열 모두에서 toString() 메서드를 호출하여 입증할 수 있습니다.
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles