Summary of the introduction to array objects in JavaScript
Array object is an array object used to store multiple values in a single variable. JS arrays are weakly typed, so the array is allowed to contain elements of different types. The array elements can even be objects or other arrays.
Syntax for creating an array
1. Array constructor
1、var list=new Array();2、var list=new Array(size);3、var list=new Array(element0,element1,...elementn);
2. Literal method
var Array[element0,element1,...elementn];
For example
var list=new Array(1,true,null,undefined,{x:1},[1,2,3]);
var list[1,true,null,undefined,{x:1},[1,2,3]];
Classification of arrays
1. Two-dimensional array. The essence of a two-dimensional array is that the elements in the array are is an array.
var arr = [[1,2],[a,b]]; alert(arr[1][0]); //a 第2列第1行所在的元素
2. Sparse array
A sparse array is an array containing discontinuous indexes starting from 0. In sparse arrays, the length attribute value is generally larger than the actual number of elements (uncommon)
Examplevar a=["a",,"b",,,,"c",,] ;
Array object properties
Properties | Function |
---|---|
length attribute | Represents the length of the array, that is, the number of elements in it |
prototype attribute | Returns a reference to the prototype of the object type |
constructor attribute | Represents the function that creates the object |
1. Length attribute
Explain the length attribute through some operationsvar arr=[1,2,3,4,5,6,7,8, 9,10];
//Defines an array containing 10 numbers.
The length attribute of the array is variable
alert(arr.length); //显示数组的长度10 arr.length=15; //增大数组的长度,length属性是可变的 alert(arr.length); //显示数组的长度已经变为15
Accessing the array elements
alert(arr[3]); //显示第4个元素的值,为4
Reduce the array length
arr.length=2; //将数组的长度减少到2,数组中的元素只剩下索引值小于2的元素 alert(arr[9]); //这时候显示第10个元素已经变为"undefined"因为索引值大于等于2的元素都被抛弃了
Restore the array length
arr.length=10; //将数组长度恢复为10 alert(arr[9]); //长度恢复之后已经抛弃的元素却无法收回,显示"undefined"
2. Prototype attribute
prototype
The attribute returns a reference to the prototype of the object type. prototype
attributes are common to object
. objectName.prototype
objectName
The parameter is the name of the object
object.
Description: Use the prototype property to provide a set of basic functions of the object's class. New instances of an object "inherit" the operations assigned to the object's prototype.
For array objects, use the following example to illustrate the use of the prototype attribute.
Add a method to the array object to return the maximum element value in the array. To accomplish this, declare a function, add it to Array.prototype, and use it.
function array_max( ) { var i, max = this[0]; for (i = 1; i < this.length; i++) { if (max < this[i]) max = this[i]; } return max; }Array.prototype.max = array_max;var x = new Array(1, 2, 3, 4, 5, 6);var y = x.max( );
After this code is executed, y holds the maximum value in the array x, or say 6.
3. Constructor attribute
The constructor
attribute represents the function that creates the object. object.constructor //object
is the name of the object or function.
Description: constructor
properties are members of all objects with prototype
. They include all JScript
intrinsic objects except Global
and Math
objects. The constructor
attribute holds a reference to the function that constructs a specific object instance.
For example:
x = new String("Hi");if (x.constructor == String) // 进行处理(条件为真)。//或function MyFunc {// 函数体。 } y = new MyFunc;if (y.constructor == MyFunc) // 进行处理(条件为真)。
For array:
y = new Array();
Object method of Array
Description : Part of it is a new feature of ECMAScript5 (not supported by IE678)
Method | Function | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
concat() | Concatenate two or more arrays and return the result | ||||||||||||
join() | Group the elements of the array Start a string | ||||||||||||
pop() | Delete and return the last element of the array | ||||||||||||
push() | Add one or more elements to the end of the array and return the new length | ||||||||||||
reverse | Reverse the order of the elements in the array | ||||||||||||
shift() | Delete and return the first element of the array | ||||||||||||
slice() | From an existing array Return the selected elements | ||||||||||||
sort() | Sort the array elements | ||||||||||||
splice() | Delete elements and add new elements to the array | ||||||||||||
Return the source code of the object | |||||||||||||
Convert the array into a string and return the result | |||||||||||||
Convert the array into a local element and return the result | |||||||||||||
Add one or more elements to the beginning of the array and return the new length | |||||||||||||
Return the original value of the array object | |||||||||||||
Traverse the array object | |||||||||||||
Do some mapping to the array | ##filter() | ||||||||||||
##every() | |||||||||||||
some() | |||||||||||||
reduce() | |||||||||||||
reduceRight() | |||||||||||||
indexOf() | |||||||||||||
Array.isArray([]) | |||||||||||||
主要对一些新特性进行讲解 var arr=[1,2,3,4,5]; arr.concat([10,11],13);//[1,2,3,4,5,10,11,13] arr.concat([1,[2,3]]);//[1,2,3,4,5,1,[1,3]] Copy after login slice var arr=[1,2,3,4,5]; arr.slice(1,3);//[2,3] arr.slice(1);//[2,3,4,5] arr.slice(1,-1);//[2,3,4] arr.slice(-4,-3);//[2] Copy after login splice var arr=[1,2,3,4,5]; arr.splice(2);//[3,4,5] arr;//[1,2];原数组被修改了 var arr=[1,2,3,4,5]; arr.splice(2,2);//[3,4] arr;//[1,2,5]; var arr=[1,2,3,4,5]; arr.splice(1,1,‘a’,‘b’);//[2] arr;//[1,"a","b",3,4,5]; Copy after login foreach var arr = [1, 2, 3, 4, 5]; arr.forEach(function(x, index, a) {//分别对应:数组元素,元素的索引,数组本身console.log(x + '|' + index + '|' + (a === arr)); });// 1|0|true// 2|1|true// 3|2|true// 4|3|true// 5|4|true Copy after login 说明:如果只有一个参数那这个参数代表数组元素,也就是数组的值,请看例2。 例2 var data=[1,2,3,4,5,6]; var sum=0; data.forEach(function(v){//其中的v就是数组的值 123456 sum+=v;}) document.write(sum+"<br>");//打印出来是21 Copy after login map var arr = [1, 2, 3]; arr.map(function(x) { return x + 10; }); // [11, 12, 13] arr; // [1, 2, 3] Copy after login filter var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; arr.filter(function(x, index) { return index % 3 === 0 || x >= 8; }); // returns [1, 4, 7, 8, 9, 10] arr; // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Copy after login every()与some() 例1 every()var arr = [1, 2, 3, 4, 5]; arr.every(function(x) { return x < 10; }); // true arr.every(function(x) { return x < 3; }); // false Copy after login some只需要有一个符合的就行 例2 somevar arr = [1, 2, 3, 4, 5]; arr.some(function(x) { return x === 3; }); // true arr.some(function(x) { return x === 100; }); // false Copy after login reduce() [x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4) Copy after login var arr = [1, 2, 3];var sum = arr.reduce(function(x, y) { return x + y }, 0); //参数 0是可选的,如果写了参数0那第一次传递的两个值就是0和1 如果不写第一次传递的就是数组的前两个值,计算结果是6 arr; //[1, 2, 3] arr = [3, 9, 6];var max = arr.reduce(function(x, y) { console.log(x + "|" + y); return x > y ? x : y; });// 3|9// 9|6 max; // 9 Copy after login reduceRight max = arr.reduceRight(function(x, y) { console.log(x + "|" + y); return x > y ? x : y; });// 6|9// 9|3max; // 9 Copy after login indexOf() var arr = [1, 2, 3, 2, 1]; arr.indexOf(2); // 1 arr.indexOf(99); // -1表示没有这个元素 arr.indexOf(1, 1); // 4 arr.indexOf(1, -3); // 4查找1从倒数第3个元素开始 arr.indexOf(2, -1); // -1查找2从倒数第1个元素开始 arr.lastIndexOf(2); // 3从右边开始找第一次出现2的位置 arr.lastIndexOf(2, -2); // 3从右边的倒数第二个开始找2出现的位置 arr.lastIndexOf(2, -3); // 1 Copy after login isArray []instanceof Array;//true ({}).toString.apply([])==='[object Array]';//true [].construcror===Array;//true Copy after login 数组和一般对象的比较
数组和字符串的比较
学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入学习交流 The above is the detailed content of Summary of the introduction to array objects in JavaScript. For more information, please follow other related articles on the PHP Chinese website! 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 UndressAI-powered app for creating realistic nude photos ![]() AI Clothes RemoverOnline AI tool for removing clothes from photos. ![]() Undress AI ToolUndress images for free ![]() Clothoff.ioAI clothes remover ![]() AI Hentai GeneratorGenerate AI Hentai for free. ![]() Hot Article
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
R.E.P.O. Save File Location: Where Is It & How to Protect It?
3 weeks ago
By DDD
![]() Hot Tools![]() Notepad++7.3.1Easy-to-use and free code editor ![]() SublimeText3 Chinese versionChinese version, very easy to use ![]() Zend Studio 13.0.1Powerful PHP integrated development environment ![]() Dreamweaver CS6Visual web development tools ![]() SublimeText3 Mac versionGod-level code editing software (SublimeText3) ![]() Hot Topics![]() The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records. ![]() 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. ![]() The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values takes a relatively long time. ![]() Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price. ![]() Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization. ![]() The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays. ![]() 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. ![]() PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group. ![]() |