JavaScript数组

JavaScript数组

复习一下数组,发现有些方法都忘记了

定义数组的方式

  1. 采用直接量创建

    var MyArray = [];//创建空数组

    var MyArray = [1,2,3];//创建数字型数组

    var MyArray = [“A”,”B”,”C”];//创建字符型数组

    var MyArray = [{id:1},{id:2},{id:3}];//创建对象型数组

  2. 采用构造函数创建

    var MyArray = new Array();
    MyArray[0] = 0;
    MyArray[1] = “A”;

    var MyArray = new Array(5);

    var MyArray = new Array(5,4,3,2,1);

属性

  • constructor

描述:返回对创建此对象的数组函数的引用

应用1:用于判断元素类型

exp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20


var test=new Array();

if (test.constructor==Array)
{
document.write("This is an Array");
}
if (test.constructor==Boolean)
{
document.write("This is a Boolean");
}
if (test.constructor==Date)
{
document.write("This is a Date");
}
if (test.constructor==String)
{
document.write("This is a String");
}

输出:

This is an Array

应用2:用于获取构造函数的原形

exp:

1
2
3
4
5
6
7
8
9
10
11
function employee(name,job,born)
{
this.name=name;
this.job=job;
this.born=born;
}

var bill=new employee("Bill Gates","Engineer",1985);

document.write(bill.constructor);

输出:

1
2
3
4
5
6
function employee(name, job, born)
{
this.name = name;
this.job = job;
this.born = born;
}
  • length

描述:设置或返回数组中元素的数目

应用:设置或返回数组中元素的数目

exp:

1
2
3
4
5
6
7
8
9
10
var arr = new Array(3)
arr[0] = "John"
arr[1] = "Andy"
arr[2] = "Wendy"

document.write("Original length: " + arr.length)
document.write("<br />")

arr.length=5
document.write("New length: " + arr.length)

输出:

Original length: 3
New length: 5
  • prototype

描述:使您有能力向对象添加属性和方法

应用:向对象添加属性和方法

exp:

Powered by Hexo and Hexo-theme-hiker

Copyright © 2019 - 2024 My Wonderland All Rights Reserved.

UV : | PV :