假设有一个包含类别和奖品数据的摄影比赛。我们可以将数据存储为数组或对象。我只是想知道哪个更好。
阵列示例:
var contest = {
'name': 'Photo Contest',
'categories': [
{'name': 'landscape', 'type': 'single'},
{'name': 'portrait', 'type': 'single'},
{'name': 'food', 'type': 'single'},
],
'prizes': [
{'name': 'winner of the year', 'count': 1, 'cat': ''},
{'name': '1st', 'count': 1, 'cat': 'landscape'},
{'name': '2nd', 'count': 3, 'cat': 'landscape'},
{'name': '3rd', 'count': 5, 'cat': 'landscape'},
{'name': '1st', 'count': 1, 'cat': 'portrait'},
{'name': '2nd', 'count': 3, 'cat': 'portrait'},
{'name': '3rd', 'count': 5, 'cat': 'portrait'},
{'name': '1st', 'count': 1, 'cat': 'food'},
{'name': '2nd', 'count': 3, 'cat': 'food'},
{'name': '3rd', 'count': 5, 'cat': 'food'}
]
}
对象示例:
var contest = {
'name': 'Photo Contest',
'categories': {
'landscape': {'type': 'single'},
'portrait': {'type': 'single'},
'food': {'type': 'single'},
},
'prizes': {
'winner of the year': {'count': 1, 'cat': ''},
'landscape 1st': {'count': 1, 'cat': 'landscape'},
'landscape 2nd': {'count': 3, 'cat': 'landscape'},
'landscape 3rd': {'count': 5, 'cat': 'landscape'},
'portrait 1st': {'count': 1, 'cat': 'portrait'},
'portrait 2nd': {'count': 3, 'cat': 'portrait'},
'portrait 3rd': {'count': 5, 'cat': 'portrait'},
'food 1st': {'count': 1, 'cat': 'food'},
'food 2nd': {'count': 3, 'cat': 'food'},
'food 3rd': {'count': 5, 'cat': 'food'},
}
}
我正在制作一个通用的竞赛管理系统。管理员用户可以通过输入一些信息(具有不同的类别和奖品)来创建新的比赛。前端页面将获取这些信息并进行显示。
这些数据可能还有其他用途,比如记录获胜者(比赛结束后)或用于搜索。
这取决于之后使用这些代码的方式
-
如果您想在以后使用这些对象来访问函数,请创建类和对象。
-
如果这是一个小程序,只需使用一个数组。除非有必要,否则不要为类或对象而烦恼。如果您正在编写
大型应用程序中的小模块,不需要其他东西
与你的代码接口,也许一个数组就足够了
取决于您的预期用例是什么。如果您想显示结果,使用数组更有意义。如果你想制作一个过滤器对话框,让用户只找到照片的特定子集,请使用对象表示,因为它可以更好地显示结果的基本结构。