loop and combine every two items

[亡魂溺海] 提交于 2020-01-06 18:02:31

问题


Ive been trying to combine two items together on each loop, in the result there is a null, how do i check the "items" so not to get null's?

var oTitle = [],
items = ['a1', 'a2', 'b1', 'b2', 'c1', 'c2'];

for (var i=0; i < items.length; i++) {
 oTitle[i] = {
    one: '' + items[i], // items[i].value
    two: '' + items[++i]
 };
}


console.log(JSON.stringify(oTitle)); 

// [{"one":"a1","two":"a2"},null,{"one":"b1","two":"b2"},null,{"one":"c1","two":"c2"}]

回答1:


Because you change the i in the for loop's body. When you call items[++i], it actually changes the i. And at the second iteration your i is not 1, but it is 2.

oTitles 0 index is ready, but at the second iteration i is 2. So you have values at 0 2 4 and so on. And for the indexes of 1,3,5 and other it has no values, so why it prints you null.

Actually for those indexes your array will contain not null, but undefined. But because you have used JSON.stringify, it converts undefined to null.

To achieve the expected result, you need to keep another variable for the indexing of your array or use push method of the array for indexing itself.

INDEX

var oTitle = [];
var index = 0;
items = ['a1', 'a2', 'b1', 'b2', 'c1', 'c2'];

for (var i=0; i < items.length; i++) {
 oTitle[index] = {
    one: '' + items[i], // items[i].value
    two: '' + items[++i]
 };
 index++;
}


console.log(JSON.stringify(oTitle)); 

PUSH

var oTitle = [];
items = ['a1', 'a2', 'b1', 'b2', 'c1', 'c2'];

for (var i=0; i < items.length; i++) {
 oTitle.push({
    one: '' + items[i], // items[i].value
    two: '' + items[++i]
 });
}


console.log(JSON.stringify(oTitle));



回答2:


Just use push() and let the indexing of new array take care of itself

var oTitle = [],
  items = ['a1', 'a2', 'b1', 'b2', 'c1', 'c2'];

for (var i = 0; i < items.length; i++) {
  oTitle.push({
    one: '' + items[i], // items[i].value
    two: '' + items[++i]
  });
}

console.log(JSON.stringify(oTitle, null, ' '))


来源:https://stackoverflow.com/questions/42044420/loop-and-combine-every-two-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!