>  기사  >  웹 프론트엔드  >  JavaScript 유형 시스템 배열 객체 연구 Notes_javascript 기술

JavaScript 유형 시스템 배열 객체 연구 Notes_javascript 기술

WBOY
WBOY원래의
2016-05-16 15:20:571165검색

배열은 순서대로 배열된 값의 집합이지만, 객체의 속성 이름은 순서가 없습니다. 기본적으로 배열은 숫자를 조회 키로 사용하는 반면 객체는 사용자 정의 속성 이름을 갖습니다. JavaScript에는 실제 연관 배열이 없지만 객체를 사용하여 연관 기능을 구현할 수 있습니다

Array()는 Object()의 특수한 유형일 뿐입니다. 즉, Array() 인스턴스는 기본적으로 몇 가지 추가 기능을 갖춘 Object() 인스턴스입니다. 배열은 모든 유형의 값을 보유할 수 있으며 이러한 값은 언제든지 업데이트되거나 삭제될 수 있으며 배열의 크기는 동적으로 조정됩니다

1. 배열 생성

Javascript의 대부분 객체와 마찬가지로 배열 객체는 Array() 생성자와 함께 new 연산자를 사용하거나 리터럴 구문을 사용하여 생성할 수 있습니다.

【1】Array 생성자를 사용하면(Array 생성자를 사용할 때 New 연산자를 생략할 수도 있음) 배열 인스턴스의 값을 쉼표로 매개변수로 구분하여 생성자에 전달할 수 있으며 Array() 생성자는 4294967295개(약 43억개) 매개변수를 수신할 수 있습니다

매개변수가 하나만 있는 경우: 값이 전달되면 배열의 길이를 설정하는 데 사용됩니다. 다른 유형의 매개변수가 전달되면 해당 값을 포함하는 항목이 하나만 있는 배열이 생성됩니다.

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
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

【2】배열 리터럴 표현을 사용하세요

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项的数组 

2. 배열 작업

배열 값을 읽어와 설정할 때 대괄호를 사용하고 해당 값의 0부터 숫자 인덱스를 제공합니다

배열의 길이 속성은 배열에 포함된 값의 개수를 나타내며 배열의 숫자 인덱스는 0부터 시작하며 길이 속성은 배열의 길이 속성을 설정하여 가능합니다. 배열 끝에서 항목을 제거하거나 배열에 새 항목을 추가할 수 있습니다. 길이가 배열의 실제 값 수보다 높게 설정된 경우 정의되지 않은 값이 배열에 추가됩니다. 길이 값의 수가 배열의 값 수보다 적게 설정된 경우 , 배열의 값이 삭제될 수 있습니다

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

배열의 크기를 초과하는 위치에 값이 배치되면 배열은 길이 값을 다시 계산합니다. 즉, 길이 값은 마지막 항목의 인덱스에 1을 더한 값과 같으며, Javascript에서는 undefine을 사용합니다. 현재 인덱스 이전의 모든 항목을 채우는 값입니다.

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

[팁] 배열 끝에 새 항목을 쉽게 추가하려면 길이 속성을 사용하세요

colors[colors.length] = '검정색';

3. 상속방법

toString()

배열에 있는 각 값의 문자열 형식을 연결하여 쉼표로 구분된 문자열을 반환합니다.

valueof()

반환되는 것은 여전히 ​​배열입니다

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()方法相同的结果

toLocaleString()

이 메서드를 호출하면 배열의 각 항목 값이 toLocaleString() 메서드를 호출합니다.

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

4. 인스턴스 메소드

배열 변환
join()

배열에서 상속된 toLocaleString(), toString() 및 valueOf() 메서드는 기본적으로 쉼표로 구분된 문자 형식으로 배열 항목을 반환합니다. Join() 메서드는 문자열을 구성하기 위해 다른 구분 기호를 사용할 수 있습니다. . 의 경우, Join() 메서드는 구분 기호로 사용되는 문자열인 하나의 매개변수만 받은 다음 모든 배열 항목이 포함된 문자열을 반환합니다. Join() 메서드에 값이 전달되지 않거나 undefed가 전달되면 쉼표가 구분 기호로 사용됩니다.

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作为分隔符

[참고] 배열의 항목 값이 null이거나 정의되지 않은 경우 값은 Join(), toLocaleString(), toString() 및 valueOf(에서 반환된 결과에서 빈 문자열로 표시됩니다. ) 방법

어레이 감지
ES3가 규정을 만든 이후 객체가 배열인지 여부를 결정하는 고전적인 문제가 발생했습니다. 일반적인 방법은 인스턴스 연산자를 사용하는 것이지만, 이 방법에는 제한이 있습니다. ES5는 특히 배열을 감지하기 위해 isArray() 메서드를 추가합니다.

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

instanceof 연산자의 문제점은 웹 페이지에 여러 프레임이 포함된 경우 전역 실행 환경이 하나만 있다고 가정한다는 것입니다. 실제로는 두 개 이상의 서로 다른 전역 환경이 있으므로 배열의 서로 다른 버전도 두 개 이상입니다. 건설자. 배열이 한 프레임에서 다른 프레임으로 전달되면 전달된 배열과 두 번째 프레임에서 기본적으로 생성된 배열의 생성자가 다릅니다

 //在不同框架中不能共享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

하지만 toString() 메서드는 다양한 프레임워크의 프로토타입 체인 전체에서 호출될 수 있습니다

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]

ES5는 Array.isArray() 메서드를 추가하여 값이 생성된 전역 환경에 관계없이 값이 배열인지 여부를 최종적으로 결정합니다.

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

栈和队列
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"

排序方法
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']

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]

   

[注意]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]

 

对于数值类型或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]

 [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]

操作方法
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]

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));//[]

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]

位置方法
  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,因为不是同一个引用

[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]

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

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.