suchen

Heim  >  Fragen und Antworten  >  Hauptteil

javascript的Array内有对象元素时,如何正确获取Array内对象;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

<code>var arrServerPoint = new Array([new ServerPoint()]);//ServerPoint为一对象类型;

 

var sp = arrServerPoint[0];

var sp2 = new ServerPoint();

 

console.log(sp);

//浏览器返回为

[ServerPoint]

    0: ServerPoint

    length: 1

    __proto__: Array[0]

 

console.log(sp2);

//浏览器返回为

ServerPoint {sPoint: H, sRadius: 1000, marker: R, circle: zc, constructor: function…}

...

__proto__: ServerPoint

 

发现先返回的对象原型不一样,所以想通过arrServerPoint[0]的方式调用ServerPoint类内的方法,返回错误;

是否我使用数组的方式不对?

请大大们帮忙!

 

*----上面问题已解决,是我粗心和基础不扎实。----

----应为:var arrServerPoint = new Array(new ServerPoint());----

----不过有又新的问题。发现修正上面问题后。通过第一种方式获取的对象类型,还是无法访问到其内部方法----

----ServerPoint类的构造函数如下----*

 

function ServerPoint(sPoint, sRadius) {

    this.sPoint = sPoint;

    this.sRadius = sRadius;

}

 

ServerPoint.prototype = {

    constructor: ServerPoint,

    setPoint: function (setPoint) {

        this.sPoint = setPoint;

    },

    getPoint: function () {

        return this.sPoint;

    },

    setRadius: function (setRadius) {

        this.sRadius = setRadius;

    },

    getRadius: function () {

        return this.sRadius;

    },

}

 

var arrServerPoint = new Array(new ServerPoint());//修改后;

 

var sp = arrServerPoint[0];

var sp2 = new ServerPoint();

</code>

console.log(sp);
//浏览器返回为

console.log(sp2);
//浏览器返回为

PHP中文网PHP中文网2910 Tage vor431

Antworte allen(2)Ich werde antworten

  • PHP中文网

    PHP中文网2017-04-10 15:12:10

    我举个简单的例子,或许你就能明白了

    1

    2

    3

    4

    5

    6

    7

    <code>var ary1 = new Array("1");

    console.log(ary1[0]); // "1"

     

    var ary2 = new Array(["1"]);

    console.log(ary2[0]); //["1"]

    console.log(ary2[0][0]); // "1"

    </code>

    Antwort
    0
  • PHPz

    PHPz2017-04-10 15:12:10

    1

    2

    <code>var arrServerPoint = new Array([new ServerPoint()]);//ServerPoint为一对象类型;

    </code>

    arrServerPoint 是一个包含了长度为1的数组的数组
    也就是arrServerPoint=[[new ServerPoint()]];

    Antwort
    0
  • StornierenAntwort