面向对象的JavaScript转换器

时间:2015-01-31 17:59:02

标签: javascript object converter

所以我在一个由JavaScript驱动的转换器应用程序中工作,现在我正在尝试使用所有措施创建一个巨大的对象。但每当我调试它时,它会说:

Expected ';' and instead saw '.' (var units.length = {};)
Expected '.' at column 1, not column 10 (var units.length = {};)
Unexpected '.' (var units.length = {};)
etc.

自从我用JS编写代码以来已经很长时间了,所以我对它有些困惑,感谢任何帮助,这里是代码:

var units = {};
var units.length = {};
var units.time = {};
var units.mass = {};
var units.temperature = {};

//Starting with Length
units.length.meter = 1;
units.length.meters = 1;

units.length.inch = 0.0254;
units.length.inches = 0.0254;

units.length.foot = 0.3048;
units.length.feet = 0.3048;

units.length.yard = 0.9144;
units.length.yards = 0.9144;

units.length.mile = 1609.344;
units.length.miles = 1609.344;

...

2 个答案:

答案 0 :(得分:6)

仅使用var声明变量,而不是创建现有对象的属性:

var units = {};
units.length = {};
units.time = {};
units.mass = {};
units.temperature = {};

//Starting with Length
units.length.meter = 1;
units.length.meters = 1;

units.length.inch = 0.0254;
units.length.inches = 0.0254;

units.length.foot = 0.3048;
units.length.feet = 0.3048;

units.length.yard = 0.9144;
units.length.yards = 0.9144;

units.length.mile = 1609.344;
units.length.miles = 1609.344;

还要考虑

var units = {
    length: {
        meter: 1,
        meters: 1,
        inch: 0.0254,
        inches: 0.0254,
        foot: 0.3048,
        feet: 0.3048,
        yard: 0.9144,
        yards: 0.9144,
        mile: 1609.344,
        miles: 1609.344
    },
    time: {},
    mass: {},
    temperature: {}
};

答案 1 :(得分:2)

在属性之前没有var,只有变量。

var units = {
    length: {},
    time: {},
    mass: {},
    temperature : {}
};

注意:长度保留为数组/字符串长度,你应该避免命名这样的属性。您应该使用扩展方法来避免重复unitsunits.length

var units = {
    length: {
        meter: 1,
        meters: 1,
        inch: 0.0254,
        inches: 0.0254 // ...
    },
    time: {},
    mass: {},
    temperature : {}
};