search

Home  >  Q&A  >  body text

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

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();

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

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

PHP中文网PHP中文网2822 days ago383

reply all(2)I'll reply

  • PHP中文网

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

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

    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"
    

    reply
    0
  • PHPz

    PHPz2017-04-10 15:12:10

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

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

    reply
    0
  • Cancelreply