简体   繁体   English

如何创建循环数组

[英]How to create array for loop

I want to create a array like this: 我想创建一个像这样的数组:

[{'b':0,'c':1,'d':2},{'b':1,'c':2,'d':3},{'b':2,'c':3,'d':4}]

How can I do this in Javascript? 如何使用Javascript执行此操作?

I have tried this: 我已经试过了:

for(i = 0; i < 3; i++){
    var b = i;
    var c = i+1;
    var d = i+2;
};
dataResult={"b":b,"c":c,"d":d};

alert(dataResult)  //not working result [{'b':0,'c':1,'d':2},{'b':1,'c':2,'d':3},{'b':2,'c':3,'d':4}] 

You are just overriding value of 'b','c','d' and at the end assigning that value to 'dataResult', so you are not getting expected result. 您只是覆盖'b','c','d'的值,最后将该值分配给'dataResult',所以您没有得到预期的结果。

Try this. 尝试这个。

 dataResult = []; for(i = 0; i < 3; i++){ dataResult.push({ 'b': i, 'c': i+1, 'd': i+2 }); }; console.log(dataResult); 

You'll have to create the object inside the loop, and then push it to the array: 您必须在循环内创建对象,然后将其推送到数组:

 const arr = []; for (let i = 0; i < 3; i++) { var b = i; var c = i + 1; var d = i + 2; arr.push({ b, c, d }); } console.log(arr); 

But it would be a bit more elegant to use Array.from here: 但是使用Array.from这里会更优雅:

 const arr = Array.from({ length: 3 }, (_, i) => { const b = i; const c = i + 1; const d = i + 2; return { b, c, d }; }); console.log(arr); 

You were creating the object outside the loop . 您正在循环外创建对象。 You need to create object inside the loop . 您需要在循环内创建对象。

Try following 尝试跟随

 var arr = []; for(let i = 0; i < 3; i++){ var b = i; var c = b+1; // as b = i, you can change c = b + 1 var d = c+1; // as c = i + 1, you can change d = c + 1 arr.push({b,c,d}); }; console.log(arr); 

Create the object inside the loop and push it to an array 在循环内创建对象并将其推送到数组

 var arr = []; for (var i = 0; i < 3; i++) { let obj = { b: i, c: i + 1, d: i + 2, } arr.push(obj) }; console.log(arr) 

 var myArr = []; for(var i = 0; i < 3; i++){ var data = i; myArr.push({ b: data, c: data + 1, d: data + 2 }) } console.log(myArr) 

You are setting the value of b, c, d after it loops so it puts the latest value of b, c, d in dataResult. 您要在循环后设置b,c,d的值,以便将b,c,d的最新值放入dataResult中。 Instead, you should initialize dataResult with an empty array and push values to the array after every step of the loop 相反,您应该使用一个空数组初始化dataResult,并在循环的每一步之后将值推入该数组

var a,b,c;
var dataResult = [];
for(i = 0; i < 3; i++){
     b = i;
     c = i+1;
    d = i+2;
dataResult.push({"b":b, "c":c, "d":d});
};

alert(dataResult);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM