Home > Web Front-end > JS Tutorial > JavaScript type system Array object study notes_javascript skills

JavaScript type system Array object study notes_javascript skills

WBOY
Release: 2016-05-16 15:20:57
Original
1205 people have browsed it

An array is a set of values ​​arranged in order. In contrast, the attribute names of objects are unordered. Essentially, arrays use numbers as lookup keys, while objects have user-defined property names. JavaScript does not have a true associative array, but objects can be used to implement associated functions

Array() is just a special type of Object(), that is, an Array() instance is basically an Object() instance with some extra functionality. Arrays can hold any type of values, these values ​​can be updated or deleted at any time, and the size of the array is dynamically adjusted

1. Array creation

Like most objects in Javascript, array objects can be created using the new operator in conjunction with the Array() constructor, or by using literal syntax

【1】Using the Array constructor (when using the Array constructor, you can also omit the New operator), you can pass the value of the array instance to the constructor, separated by commas as parameters, and the Array() constructor can receive 4294967295 (approximately 4.3 billion) parameters

If there is only one parameter: if a value is passed, it will be used to set the length of the array; if another type of parameter is passed, an array with only one item containing that value will be created

var colors;
console.log(colors = new Array(),colors.length);//[] 0
console.log(colors = new Array('red','blue','green'),colors.length);//['red','blue','green'] 3
console.log(colors = new Array(20),colors.length);//[] 20
console.log(colors = new Array('red'),colors.length);//['red'] 1
Copy after login
var foo = new Array(1,2,3);
var bar = new Array(100);
console.log(foo[0],foo[2]);//1 3
console.log(bar[0],bar.length);//undefined 100
Copy after login

【2】Use array literal representation

var colors = ['red','blue','green'];
var colors = [];



//Array构造函数
var myArray1 = new Array('blue','green','orange','red');
console.log(myArray1);//['blue','green','orange','red']
//数组字面量表示法
var myArray2 = ['blue','green','orange','red'];
console.log(myArray2);//['blue','green','orange','red']



var colors = [1,2,]; 
//在IE8及以前中会包含一个三个项目,且每个项目为1、2和undefined的数组。在其他浏览器中为只包含1和2的数组
var colors = [,,,];
 //在IE8及以前会创建4项的数组,而在其他浏览器中会创建3项的数组 

Copy after login

2. Array operations

When reading and setting array values, use square brackets and provide the 0-based numeric index of the corresponding value

The length attribute of the array represents the number of values ​​in the array, and the numeric index of the array starts from 0; and the length attribute is readable and writable. By setting the Length attribute of the array, you can remove items from the end of the array or Adds new items to the array. If the length is set higher than the actual number of values ​​in the array, undefined values ​​will be added to the array; if the number of length values ​​is set less than the number of values ​​in the array, values ​​in the array may be deleted

var myArray = ['blue','green','orange','red'];
console.log(myArray.length);//4
myArray.length = 99;
console.log(myArray.length);//99
myArray.length = 1;
console.log(myArray[1]);//undefined
console.log(myArray);//['blue']

 

var colors = ['red','blue','green'];
colors.length = 2;
alert(colors[2]);//undefined
colors.length = 4;
alert(colors[3]);//undefined

Copy after login

When a value is placed at a position that exceeds the size of the array, the array will recalculate its length value, that is, the length value is equal to the index of the last item plus 1, and Javascript will use undefined values ​​to fill all items before the current index. Index

var myArray = [];
myArray[50] = 'blue';
console.log(myArray.length);//51
var colors = ['red','blue','green'];
colors[99] = 'black';
console.log(colors.length);//100  
Copy after login

[tips] Use the length attribute to easily add new items at the end of the array

colors[colors.length] = 'black';

3. Inheritance method

toString()

Returns a comma-separated string

concatenated from the string form of each value in the array

valueof()

What is returned is still an array

var colors = ['red','blue','green'];         
console.log(colors.valueOf());//['red','blue','green']
alert(colors.valueOf());//'red,blue,green' 
alert(colors.toString());//'red,blue,green'
alert(colors);//'red,blue,green'[注意]由于alert()要接收字符串参数,它会在后台调用toString()方法,会得到与toString()方法相同的结果

Copy after login

toLocaleString()

When calling this method, the value of each item in the array calls the toLocaleString() method

var person1 = {
  toLocaleString: function(){
    return 'Nikolaos';
  },
  toString: function(){
    return 'Nicholas';
  }
};
var person2 = {
  toLocaleString: function(){
    return 'Grigorios';
  },
  toString: function(){
    return 'Greg';
  }
};

var people = [person1,person2];
alert(people);//Nicholas,Greg
alert(people.toString());//Nicholas,Greg
alert(people.toLocaleString());//Nikolaos,Grigorios
Copy after login

4. Instance methods

Array conversion
join()

The toLocaleString(), toString(), and valueOf() methods inherited by the array will return the array items in the form of comma-separated characters by default; the join() method can use different delimiters to construct the string. , the join() method only receives one parameter, a string used as a delimiter, and then returns a string containing all array items. If no value is passed to the join() method, or undefined is passed, a comma is used as the separator

var colors = ['red','green','blue'];
console.log(colors.join(','));//'red,green,blue'
console.log(colors.join('||'));//'red||green||blue'
console.log(colors.join());//'red,green,blue'
console.log(colors.join(undefined));//'red,green,blue'[注意]IE7-会使用undefined作为分隔符
Copy after login

[Note] If the value of an item in the array is null or undefined, the value will be represented by an empty string in the results returned by the join(), toLocaleString(), toString() and valueOf() methods

Array detection
Since ES3 made the regulations, the classic problem of determining whether an object is an array has arisen. The common method is to use the instance operator, but this method has its limitations; ES5 specifically adds the isArray() method to detect arrays

var value = [123];
console.log(value instanceof Array);//true
Copy after login

The problem with the instanceof operator is that it assumes that there is only one global execution environment. If the web page contains multiple frames, there are actually more than two different global environments, and thus more than two different versions of the Array constructor. If an array is passed from one frame to another, the array passed in and the array created natively in the second frame have different constructors

 //在不同框架中不能共享prototype属性
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
var value = new window.frames[0].Array;
console.log(value instanceof Array);//false
console.log(value.constructor == Array);//false
Copy after login

However, the toString() method can be called across prototype chains in different frameworks

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
var value = new window.frames[0].Array;
console.log(Object.prototype.toString.call(value));//[object Array]
Copy after login

ES5 adds the Array.isArray() method to ultimately determine whether a value is an array, regardless of the global environment in which it was created

Array.isArray()

var value = [123];
console.log(Array.isArray(value));//true
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
var value = new window.frames[0].Array;
console.log(Array.isArray(value));//true
Copy after login

栈和队列
push()

  可以接收任意数量的参数,把它们逐个添加到数组末尾,并返回修改后数组的长度

pop()

  从数组末尾移除最后一项,减少数组的length值,然后返回移除的项

shift()

  移除数组中的第一个项并返回该项,同时数组的长度减1(结合使用shift()和push()可以模拟队列)

unshift()

  在数组前端添加任意个项并返回新数组长度(结合使用unshift()和pop()从相反方向模拟队列)

  [注意]IE7-浏览器unshift()方法返回的总是undefined

var colors = [];
var count = colors.push('red','green');
console.log(colors,count);//['red','green'] 2
var count = colors.pop();
console.log(colors,count);//['red'] 'green'
var count = colors.unshift('white','black');
console.log(colors,count);//["white", "black", "red"] 3
var count = colors.shift();
console.log(colors,count);//["black", "red"] "white"

Copy after login

排序方法
reverse()

  反转数组的顺序,返回经过排序之后的数组;而原数组顺序也发生改变

var array = [1,2,4,3,5];
console.log(array,array.reverse());//[5,3,4,2,1] [5,3,4,2,1]
var array = ['str',true,3];
console.log(array,array.reverse());//[3,true,'str'] [3,true,'str']
Copy after login

sort()

  默认情况下,按字符串升序排列数组项,sort方法会调用每个数组项的toString()方法,然后比较得到的字符串排序,返回经过排序之后的数组,而原数组顺序也发生改变

var array = [1,2,4,3,5];
console.log(array,array.sort());//[1,2,3,4,5] [1,2,3,4,5]
var array = ['3str',3,2,'2'];
console.log(array,array.sort());//[2, "2", 3, "3str"] [2, "2", 3, "3str"]
var array = [1,5,10,50];
console.log(array,array.sort());//[1, 10, 5, 50] [1, 10, 5, 50]

Copy after login
  

[注意]sort()方法可以接受一个比较函数作为参数,以便指定哪个值在哪个值的前面。比较函数接收两个参数,如果第一个参数应该位于第二个参数之前则返回一个负数,如果两个参数相等则返回0,如果第一个参数应该位于第二个参数之后则返回一个正数

[tips]比较函数

 function compare(value1,value2){
  if(value1 < value2){
    return -1;
  }else if(value1 > value2){
    return 1;
  }else{
    return 0;
  }
}
var array = ['5px',50,1,10];
//当数字与字符串比较大小时,字符串'5px'会被转换成NaN,这样结果就是false
console.log(array.sort(compare));//["5px",1, 10, 50]

 

Copy after login

对于数值类型或valueOf()方法会返回数值类型的对象类型,比较函数可以简化为:

function compare(value1,value2){
  return value1 - value2;
}
var array = ['5px',50,1,10];
console.log(array.sort(compare));//["5px",1,10,50]
var array = [5,50,1,10];
console.log(array.sort(compare));//[1,5,10,50]

Copy after login

[tips]创建一个随机数组

function compare(){
  return Math.random() - 0.5;
}
var array = [1,2,3,4,5];
console.log(array.sort(compare));//[2,1,5,4,3]
Copy after login

操作方法
concat()

  基于当前数组中的所有项创建一个新数组,先创建当前数组一个副本,然后将接收到的参数添加到这个副本的末尾,最后返回新构建的数组(concat()不影响原数组)

  如果不给concat()方法传递参数时,它只是复制当前的数组;如果参数是一个或多个数组,则该方法会将这些数组中的每一项都添加到结果数组中;如果传递的值不是数组,这些值就会被简单地添加到结果数组的末尾

var numbers = [1,2];
console.log(numbers,numbers.concat());//[1,2] [1,2]
console.log(numbers,numbers.concat([5,4,3],[3,4,5],1,2));//[1,2] [1,2,5,4,3,3,4,5,1,2]
Copy after login

slice()

  基于当前数组中的一个或多个项创建一个新数组,接受一个或两个参数,即要返回项的起始和结束位置,最后返回新数组(slice()不影响原数组)

  如果没有参数,则返回原数组;如果只有一个参数时,slice()方法返回从该参数指定位置开始到当前数组末尾的所有项;若有两个参数时,该方法返回起始位置和结束位置之间的项,但不包括结束位置的项;若参数为负数时,则用数组长度加负数作为参数;若结束位置小于开始位置,则返回空数组

var numbers = [1,2,3,4,5];
console.log(numbers.slice());//[1,2,3,4,5]
console.log(numbers.slice(2));//[3,4,5]
console.log(numbers.slice(2,3));//[3]
console.log(numbers.slice(-3));//-3+5=2 -> [3,4,5]
console.log(numbers.slice(2,1));//[]

Copy after login

splice()

  原数组变为修改后的数组,而splice()返回从原数组中删除的项组成的数组,若无删除项则返回空数组。若第一个参数为负数时,则用数组长度加负数作为参数;若第二个参数为负数时,则用0作为参数

  [1]删除:两个参数为要删除的第一项的位置、要删除的项数

  [2]插入:三个参数为起始位置、0(要删除的基数)、要插入的项

  [3]替换:三个参数为起始位置、要删除的项数、要插入的项

 var numbers = [1,2,3,4,5];
console.log(numbers.splice(),numbers);//[] [1, 2, 3, 4, 5]
console.log(numbers.splice(0,2),numbers);//[1,2] [3,4,5]
var numbers = [1,2,3,4,5];
console.log(numbers.splice(1,0,11,12),numbers);//[] [1,11,12,2,3,4,5]
var numbers = [1,2,3,4,5];
console.log(numbers.splice(1,3,11,12),numbers);//[2,3,4] [1,11,12,5] 
var numbers = [1,2,3,4,5];
console.log(numbers.splice(-4,3,11,12),numbers);//-4+5=1 -> [2,3,4] [1,11,12,5] 
var numbers = [1,2,3,4,5];
console.log(numbers.splice(-4,-3,11,12),numbers);//-4+5=1 -> [] [1,11,12,2,3,4,5]

Copy after login

位置方法
  ES5为数组实例添加了两个位置方法indexOf()、lastIndexOf()。这两个方法都接收两个参数:要查找的项、表示查找起点位置的索引(可选)。返回第一个满足条件的查找项在数组中的位置,如果没有找到则返回-1(位置方法不会影响原数组)

  [注意]方法在比较参数时,使用的是全等操作符

indexOf()     从前向后查找
lastIndexOf()   从后向前查找

var numbers = [1,2,3,4,5,4,3,2,1];
console.log(numbers.indexOf(4));//3
console.log(numbers.lastIndexOf(4));//5
console.log(numbers.indexOf(4,4));//5
console.log(numbers.lastIndexOf(4,4));//3

 

var person = {name: 'Nicholas'};
var people = [{name: 'Nicholas'}];
var morePeople = [person];
alert(people.indexOf(person));//-1,因为person和people[0]虽然值相同,但是是两个引用
alert(morePeople.indexOf(person));//0,因为person和morepeople[0]是同一个引用
alert(morePeople.indexOf({name: 'Nicholas'}));//-1,因为不是同一个引用

Copy after login

[tips]返回满足条件的项的所有索引值

function allIndexOf(array,value){
  var result = [];
  var pos = array.indexOf(value);
  if(pos === -1){
    return -1;
  }
  while(pos > -1){
    result.push(pos);
    pos = array.indexOf(value,pos+1);
  }
  return result;
}
var array = [1,2,3,3,2,1];
console.log(allIndexOf(array,1));//[0,5]
Copy after login

以上就是本文的详细内容,希望对大家的学习javascript程序设计有所帮助。

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template