1

好的,我忘记了链接到列表中已经存在的单个变量的变量列表的名称是什么,但请看一下:

function Models(Make) {
    var cars = {
        "Acura": ['Integra', 'NSX', 'RSX', ],
        "BMW": ['M3', ],
        "Buick": ['Regal', ],
        "Cadillac": ['CTS', ],
        "Honda": ['Accord', 'Civic', 'CR-Z', 'Prelude', ],
        "Mazda": ['3', 'MX-5', 'MX-6', 'RX-7', 'RX-8', ],
        "Mini": ['Cooper', ],
        "Nissan": ['240SX', '350Z', 'Fairlady', 'GT-R', 's13', 's14', 's15', ],
        "Toyota": ['Celica', 'MR2', 'Supra', ],
    };
    var holder = cars[Make]
    var Model = holder[Math.floor(Math.random() * holder.length)];
    return Model;
}

function main() {
    var Makes = [
            'Acura',
            'BMW',
            'Buick',
            'Cadillac',
            'Honda',
            'Mazda',
            'Mini',
            'Nissan',
            'Toyota',
    ];
    var Make = Makes[Math.floor(Math.random() * Makes.length)];
    var Model = Models(Make);
    var Out = Make + " " + Model;
    return Out;
}

document.write(main());

我想在车辆型号之后添加第三类(例如 Mini Cooper “S” 或 Honda Civic “Del Sol”),我该怎么做?

4

2 回答 2

3

您的cars对象包含许多属性,这些属性都是Arrays,并且这些Arrays 被索引,包含Strings。

如果您想存储的不仅仅是一个字符串(模型),那么您必须将其更改为数组或对象:

var cars = {
    "Acura": [
        {
            base: 'Integra'
            submodals: ['S', 'Coupe', 'Si']
        },
        {
            base: 'NSX',
            submodels: ['A', 'B', 'C']
        },
        // ...
    ]
}
于 2013-04-02T17:39:08.493 回答
1

我会编写一个函数,它可以将任意深度的嵌套对象作为参数。然后像这样构造它:

var cars = {
    "Acura": {
        "Integra": ['S', 'Coupe', 'Si'],
        "NSX": "",
        "RSX": ""
    },
    "BMW": ['M3'],
    "Buick": ['Regal'],
    "Cadillac": ['CTS'],
    "Honda": {
        "Accord": "",
        "Civic": ["Del Sol"],
        "CR-Z": "",
        "Prelude": ""
    },
    "Mazda": ['3', 'MX-5', 'MX-6', 'RX-7', 'RX-8'],
    "Mini": {
        "Cooper": ["S"]
    },
    "Nissan": ['240SX', '350Z', 'Fairlady', 'GT-R', 's13', 's14', 's15'],
    "Toyota": ['Celica', 'MR2', 'Supra']
};
// (and notice: no trailing commas!)

然后你可以递归地选择一个随机模型:

function main() {
    return getRandom(cars).join(" ");
}
function getRandom(o) {
    if (o instanceof Array)
        return o.slice(~~(Math.random()*o.length), 1); // a random item in an array
    // else
    var props = Object.keys(o),
        r = props[ ~~(Math.random()*props.length) ],
        p = o[r];
    if (typeof p == "object") {
        var res = getRandom(p); // recurse
        res.unshift(r);
        return res;
    } // else
    return [ r ]; // an array literal with the random key
}
于 2013-04-02T18:43:06.023 回答