数字转换为对象

时间:2012-08-06 13:00:58

标签: javascript

我遇到了一些javascripting的麻烦,其中一些值很大的数字,突然变成了对象,我无法弄清楚如何或为什么。

codesnippets:

addFigure("-1,1,-0.5_1,1,-0.5_0.5,-1,-0.5_-0.5,-1,-0.5");

function addFigure(t) {
        var fig = new figure();
        var v = t.split("_");

        var points = new Array();
        for (var i = 0; i < v.length; i++) {
            var coords = v[i].split(",");
            var x = parseFloat(coords[0]);
            var y = parseFloat(coords[1]);
            var z = parseFloat(coords[2]);
            alert(typeof x + " " +typeof y)
            var point = new Point3D(x, y, z);
            alert(typeof point.x + " " + typeof point.y)
           //both alerts print out "number number"
           fig.addPoint(point);
        }


        figures.push(fig);
    }

        function figure() {
        this.points = new Array();
        this.addPoint = function (x, y, z) {
            var v = new Point3D(x, y, z);
            alert(typeof x + " " + typeof y)
//this alert prints out "Object undefined"
            this.points.push(v)
        }

        this.getPoints = function () { return this.points }

    }

2 个答案:

答案 0 :(得分:2)

您在这里使用一个参数(addPoint)调用Point3D函数:

fig.addPoint(point);

addPoint似乎期望这一点成为三个独立的参数:

this.addPoint = function (x, y, z) {

因此,最终x成为您传入的Point3Dyzundefined

答案 1 :(得分:2)

您的addPoint()方法似乎希望单独传递xyz属性,但您只传递一个参数{{1对象。

将方法更改为:

point

或者将调用更改为方法

this.addPoint(point) {
    /* x, y and z are now retrievable from point.x, point.y etc */
}