search
HomeWeb Front-endJS TutorialType of object: local object (1)_Basic knowledge

在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
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft