在 Javascript 中创建对象列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5868850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:17:02  来源:igfitidea点击:

creating list of objects in Javascript

javascript

提问by user517406

Is it possible to do create a listof your own objects in Javascript? This is the type of data I want to store :

是否可以在 中创建list自己的对象Javascript?这是我要存储的数据类型:

Date : 12/1/2011   Reading : 3   ID : 20055    
Date : 13/1/2011   Reading : 5   ID : 20053    
Date : 14/1/2011   Reading : 6   ID : 45652

回答by Darin Dimitrov

var list = [
    { date: '12/1/2011', reading: 3, id: 20055 },
    { date: '13/1/2011', reading: 5, id: 20053 },
    { date: '14/1/2011', reading: 6, id: 45652 }
];

and then access it:

然后访问它:

alert(list[1].date);

回答by tbradley22

dynamically build list of objects

动态构建对象列表

var listOfObjects = [];
var a = ["car", "bike", "scooter"];
a.forEach(function(entry) {
    var singleObj = {};
    singleObj['type'] = 'vehicle';
    singleObj['value'] = entry;
    listOfObjects.push(singleObj);
});

here's a working example http://jsfiddle.net/b9f6Q/2/see console for output

这是一个工作示例http://jsfiddle.net/b9f6Q/2/查看控制台输出

回答by nacho

Maybe you can create an array like this:

也许你可以创建一个这样的数组:

     var myList = new Array();
     myList.push('Hello');
     myList.push('bye');

     for (var i = 0; i < myList .length; i ++ ){
        window.console.log(myList[i]);
     }

回答by Blexy

Going off of tbradley22's answer, but using .mapinstead:

离开 tbradley22 的答案,而是使用.map

var a = ["car", "bike", "scooter"];
a.map(function(entry) {
    var singleObj = {};
    singleObj['type'] = 'vehicle';
    singleObj['value'] = entry;
    return singleObj;
});

回答by DVeen

So, I'm used to use

所以,我习惯使用

var nameOfList = new List("objectName", "objectName", "objectName")

This is how it works for me but might be different for you, I recommend to watch some Unity Tutorials on the Scripting API.

这对我来说是这样的,但对你来说可能会有所不同,我建议观看一些关于脚本 API 的 Unity 教程。