search
HomeWeb Front-endJS TutorialJavascript_3_ Array object

Javascript_3_ Array object

Jan 18, 2017 pm 04:27 PM

Javascript_3_ Array object

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=GBK" />
    <title>javascript演示5_ Array 对象</title>
    </head>
    <body>
    <h1 id="javascript演示-nbsp-Array-nbsp-对象">javascript演示5_ Array 对象</h1>
    <script type="text/javascript" src="a.js">    </script>
    <script type="text/javascript">
     /*
         * Array 对象
提供对创建任何数据类型的数组的支持。
arrayObj = new Array()
arrayObj = new Array([size])
arrayObj = new Array([element0[, element1[, ...[, elementN]]]])
参数
arrayObj
必选项。要赋值为 Array 对象的变量名。
size
可选项。可选项数组的大小。由于数组的下标是从零开始,
创建的元素的下标将从零到 size -1。
element0,...,elementN
可选项。要放到数组中的元素。
这将创建具有 n + 1 个元素的长度为 n + 1 的数组。
使用该语法时必须有一个以上元素。
说明
创建数组后,能够用 [ ] 符号访问数组单个元素,例如: 
var my_array = new Array();
for (i = 0; i < 10; i++)
   {
   my_array[i] = i;
   }
x = my_array[4];
由于 Microsoft JScript 中的数组的下标是从零开始的,
前面例子中最后一条语句访问数组的第五个元素。
该元素中保存的值是 4。 
如果只向 Array 的构造函数传递了一个参数,而该参数是数字,
则它必须是无符号32位整数(大约40亿)。该值成为数组的大小。
如果该值为数值,但小于0或不为整数,发生运行时错误。
如果传递给 Array 构造函数的是单个值并且不是数值,
设置 length 属性为1,而且唯一的元素值成为单个的传入的参数。
请注意 JScript 数组为解析数组,也就是尽管可以分配多个元素给一个数组,
但实际上只有包含数据的元素才存在。这减少了数组使用的内存数量。
         */
        array=new Array();
        //array1=new Array(size);
        //array2=new Array(e1,e2,e3);
        var arr1=[2,4,6,7];
        var arr2=["nba","xixi","abc"];
        var arr3=["qq","baidu"];
        println(arr1.concat(arr2,arr3));
//        2,4,6,7,nba,xixi,abc,qq,baidu
        println(arr1.concat("mm",arr3));
        //2,4,6,7,mm,qq,baidu
        println(arr1.join());
        println(arr1.join(","));
        println(arr1.join("-"));
        //2,4,6,7
        //2,4,6,7
        //2-4-6-7
        function myJoin(arr,separator){
        	var str="";
        	for (var i=0; i < arr.length; i++) {
                if (i!=arr.length-1) {
                	str+=arr[i]+separator;
                } else{
                	str+=arr[i];
                }
        	}
        	return str;
        }
        println(myJoin(arr3,"_"));
        //Array.prototype.myjoin=myJoin();如果加入原型,就要改用this
        /*
         * pop方法:移除数组最后一个元素,并返回该元素!(removeLast)
         * 如果数组为空,返回undefined
         * pop 方法
移除数组中的最后一个元素并返回该元素。
arrayObj.pop( )
必选的 arrayObj 引用是一个 Array 对象。
说明
如果该数组为空,那么将返回 undefined。
         * 
         * 
         * push 方法
将新元素添加到一个数组中,并返回数组的新长度值。
arrayObj.push([item1 [item2 [. . . [itemN ]]]])
参数
arrayObj
必选项。一个 Array 对象。
item, item2,. . . itemN
可选项。该 Array 的新元素。
说明
push 方法将以新元素出现的顺序添加这些元素。
如果参数之一为数组,那么该数组将作为单个元素添加到数组中。
如果要合并两个或多个数组中的元素,请使用 concat 方法。
         * 
         * 
         * shift 方法
移除数组中的第一个元素并返回该元素。(removeFirst)
arrayObj.shift( )
必选的 arrayObj 引用是一个 Array 对象。
说明
shift 方法可移除数组中的第一个元素并返回该元素。
         * 
         * 
         * slice 方法 (Array)
返回一个数组的一段。
arrayObj.slice(start, [end]) (包含头,不包含尾)
参数
arrayObj
必选项。一个 Array 对象。 
start 
必选项。arrayObj 中所指定的部分的开始元素是从零开始计算的下标。 
end 
可选项。arrayObj 中所指定的部分的结束元素是从零开始计算的下标。
说明
slice 方法返回一个 Array 对象,其中包含了 arrayObj 的指定部分。 
slice 方法一直复制到 end 所指定的元素,但是不包括该元素。
如果 start 为负,将它作为 length + start处理,
此处 length 为数组的长度。如果 end 为负,
就将它作为 length + end 处理,此处 length 为数组的长度。
如果省略 end ,那么 slice 方法将一直复制到 arrayObj 的结尾。
如果 end 出现在 start 之前,不复制任何元素到新数组中。
示例
在下面这个例子中,除了最后一个元素之外,
myArray 中所有的元素都被复制到 newArray 中: 
newArray = myArray.slice(0, -1)
         * 
         * 
         * splice 方法
从一个数组中移除一个或多个元素,如果必要,
在所移除元素的位置上插入新元素,返回所移除的元素。
arrayObj.splice(start, deleteCount, [item1[, item2[, . . . [,itemN]]]])
参数
arrayObj
必选项。一个 Array 对象。
start
必选项。指定从数组中移除元素的开始位置,
这个位置是从 0 开始计算的。
deleteCount
必选项。要移除的元素的个数。
item1, item2,. . .,itemN
必选项。要在所移除元素的位置上插入的新元素。
说明
splice 方法可以移除从 start 位置开始的指定个数的元素并插入新元素,
从而修改 arrayObj。返回值是一个由所移除的元素组成的新 Array 对象。
         * 
         * 
         * unshift 方法
将指定的元素插入数组开始位置并返回该数组。(addFirst)
arrayObj.unshift([item1[, item2 [, . . . [, itemN]]]])
参数
arrayObj
必选项。一个 Array 对象。
item1, item2,. . .,itemN
可选项。将插入到该 Array 开始部分的元素。
说明
unshift 方法将这些元素插入到一个数组的开始部分,
所以这些元素将以参数序列中的次序出现在数组中。
         * 
         * 
         */
        /*
         * 
         * join 方法
返回字符串值,其中包含了连接到一起的数组的所有元素,
元素由指定的分隔符分隔开来。
arrayObj.join(separator)
参数
arrayObj
必选项。Array 对象。
separator
必选项。是一个 String 对象,
作为最终的 String 对象中对数组元素之间的分隔符。
如果省略了这个参数,那么数组元素之间就用一个逗号来分隔。
说明
如果数组中有元素没有定义或者为 null,将其作为空字符串处理。
示例
下面这个例子说明了 join 方法的用法。 
function JoinDemo(){
   var a, b;
   a = new Array(0,1,2,3,4);
   b = a.join("-");
   return(b);
}
         * 
         * 
         * 
         * concat方法:返回一个新数组,由两个或多个数组组合而成
         * concat 方法 (Array)
返回一个新数组,这个新数组是由两个或更多数组组合而成的。
array1.concat([item1[, item2[, . . . [, itemN]]]])
必选项。其他所有数组要进行连接的 Array 对象。 
item1,. . ., itemN
可选项。要连接到 array1 末尾的其他项目。
说明
concat 方法返回一个 Array 对象,
其中包含了 array1 和提供的任意其他项目的连接。
要加的项目(item1 … itemN)会按照从左到右的顺序添加到数组。
如果某一项为数组,那么添加其内容到 array1 的末尾。
如果该项目不是数组,就将其作为单个的数组元素添加到数组的末尾。
以下为从源数组复制元素到结果数组: 
对于从正被连接到新数组的数组中复制的对象参数,
复制后仍然指向相同的对象。不论新数组和源数组中哪一个有改变,
都将引起另一个的改变。 
对于连接到新数组的数值或字符串,只复制其值。
一个数组中值有改变并不影响另一个数组中的值。 
下面这个例子说明了使用数组时 concat 方法的用法: 
function ConcatArrayDemo(){
   var a, b, c, d;
   a = new Array(1,2,3);
   b = "JScript";
   c = new Array(42, "VBScript);
   d = a.concat(b, c);
   // 返回数组 [1, 2, 3, "JScript", 42, "VBScript"]
   return(d);
}
         */
        //JS用数组模拟队列数据结构
        var arr=[];
        arr.unshift("1","2","3");//插入数组开头,返回该数组
        println(arr);//123
        var arr2=[];
        arr2.unshift("A");
        arr2.unshift("B");
        arr2.unshift("C");
        println(arr2);//C,B,A因为unshift是插入开头
        //pop移除并返回数组中最后一个元素
        //与unshift结合,形成队列结构
        println(arr2.pop());
        println(arr2.pop());
        println(arr2.pop());//此时arr2已经为空!
        //A,B,C
        arr2.unshift("A");
        arr2.unshift("B");
        arr2.unshift("C");
        println(arr2);//C,B,A因为unshift是插入开头
        //结合shift(移除并返回第1个元素),可模拟堆栈结构
        println(arr2.shift());
        println(arr2.shift());
        println(arr2.shift());
        //C,B,A
        //给数组原型加入方法:求最大值
        Array.prototype.getMax=function(){
        	var temp=0;
        	for (var i=0; i < this.length; i++) {
        	  if (this[i]>this[temp]) {
        	  	temp=i;
        	  }
        	}
        	return this[temp];
        }
        println(arr1);//2,4,6,7
        println(arr1.getMax());//7
        //给数组原型加入自定义的打印方法
        Array.prototype.toString=function(){
        	return "【"+this.join(", ")+"】" ;
        }
        println(arr1);//【2, 4, 6, 7】
    </script>
    </body>
</html>

The above is the content of Javascript_3_ Array object. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


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: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 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.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 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 Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

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

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 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.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool