所以我可以使用下面的代码创建一大堆独立的空对象。有一个更好的方法吗?或者这是唯一的方法吗?
var array = [];
for (let i = 0; i < 5; i++)
{
array.push("temp" + i);
}
for (let item of array)
{
eval(`${item} = new Object();`);
}
temp0.first = 1;
temp4.last = "last";
for (let item of array)
{
console.log(eval(item));
}
答案 0 :(得分:2)
只需使用一个对象:
var objects = {};
for (let i = 0; i < 5; i++)
{
objects["temp" + i] = {};
}
访问:
objects["temp0"]
或:
objects.temp0
或者,如果您想污染可以使用的全局命名空间:
for (let i = 0; i < 5; i++)
{
window["temp" + i] = {};
}
使用以下方式访问:
temp0
temp1 //etc.
或:
window["temp0"] //just like above
答案 1 :(得分:2)
y(t)=Yo/Yo+(1-Yo)e^-at
答案 2 :(得分:1)
就是这样:
function makeMadObjects(num){
var a = [];
for(var i=0; i<num; i++){
a.push({});
}
return a;
}
var arrayOfObjects = makeMadObjects(27);
arrayOfObjects[4].someProperty = 'some value';
console.log(arrayOfObjects);
答案 3 :(得分:1)
您可以使用解构赋值为数组中的对象赋值变量,或者将属性名设置为具有动态.length
的数组中的对象,然后使用数组和属性名中的对象索引从数组中检索特定对象属性是普通对象的对象
let n = 5; // `n`: dynamic; e.g.; Math.floor(Math.random() * 100);
let temps = Array.from({length: n}, (_, i) => ({}));
let len = temps.length;
let [temp0, temp1, temp2, temp3, temp4 /* , ..tempN < len */ ] = temps;
console.log(temp0, temp4);
&#13;
let n = 5 // Math.floor(Math.random() * 100);
let temps = Array.from({length:n}, (_, i) => ({[`temp${i}`]:{}}));
// set, get `temp0` through `tempN`, when needed for application,
// where `N` is less than `n`, e.g.; set, get `temp0`, `temp4`
let {0:{temp0}, 4:{temp4}} = temps;
console.log(temp0, temp4);
&#13;