如何从函数中返回多个变量?

时间:2017-08-01 16:27:55

标签: javascript arrays for-loop

编辑:

最终我想打印出这样的东西: 滑板车有3种材料:“木”,“金属”,“玻璃”;棒球棒有两种材料:“木头”,金属“仅使用for循环。

我正在使用以下内容:

var data = [
    {
     "title": "scooter", 
     "materials": ["wood", "metal", "glass"]
    }, 
   {
    "title": "baseball bat", 
    "materials": ["wood", "metal"]
   },
  {
    "title": "coffee table", 
    "materials": ["wood"]
  }];

我以为我可以使用for循环进行简单的传递来获取标题,计数,并创建一个类似这样的数组:

 function testing () {
   let items = []; //contains the titles
   let container = []; //contains the materials
   let count = 0; //count of items
   for (let i=0; i<data.length; i++){
    if (data[i].materials.length > 2){
    container.push(data[i].materials); 
    count = data[i].materials.length;
    items.push(data[i].title)
   }
  }return container;
 }
console.log(testing);

我不知道代码是否正确以获得我想要的东西。有什么想法吗?

编辑:所以当我运行此代码时,我只是获取材料列表。在做返回项目和console.log(测试)时;我收到了一份物品清单。

看起来,计数只是获得不属于材料的标题的数组计数。

使用其他代码进一步编辑:

function testing () {
  let items = []; 
  let container = []; 
  let count = 0; 
  let result = '';
   for (let i=0; i<data.length; i++){
    if (data[i].materials.length > 2){
      container.push(data[i].materials); 
      items.push(data[i].title)
       for (let j=0; j<container.length; j++){
        result= `${items[j]} has materials :${container[j]}`;
       }
     }
   }return result;
 }
console.log(testing());

通过上面的内容,我可以得到最后一个标题,表明它符合带有项目列表的if语句。然而,我无法计算这些材料。例如,它只是显示: 棒球棒有木材,金属材料

我面临的问题是如何获取计数然后显示匹配的所有对象。所以它会改为: 滑板车有3种材料:木材,金属,玻璃 棒球棒有2种材料:木材,金属

6 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你真的不需要循环。数组有map方法,可以将你的函数应用于数组的每个元素。

var data = [
    {
     "title": "scooter", 
     "materials": ["wood", "metal", "glass"]
    }, 
   {
    "title": "baseball bat", 
    "materials": ["wood", "metal"]
   },
  {
    "title": "coffee table", 
    "materials": ["wood"]
  }];
 
var result = data.map(item => `${item.title} has ${item.materials.join(', ')}`).join('\n') 
console.log(result);

请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

答案 1 :(得分:0)

查看以下代码是否以任何方式为您提供帮助:

SyncReplicasOptimizer

答案 2 :(得分:0)

您需要做的就是映射每个项目并连接格式化的字符串。

您需要知道要显示数量的材料数量。

&#13;
&#13;
const capitalize = s => s.charAt(0).toUpperCase() + s.substr(1);
const quantity = x => 'one,two,three,four,...'.split(',')[x - 1];

var data = [{
    "title": "scooter",
    "materials": ["wood", "metal", "glass"]
  }, {
    "title": "baseball bat",
    "materials": ["wood", "metal"]
  }, {
    "title": "coffee table",
    "materials": ["wood"]
  }
];

console.log(data.map(item => {
  return [
    capitalize(item.title),
    ' has ',
    quantity(item.materials.length),
    ' material' + (item.materials.length > 1 ? 's' : '') + ': ',
    item.materials.map(material => {
      return '"' + material + '"';
    }).join(', ')
  ].join('');
}).join('; '));
&#13;
.as-console-wrapper { top: 0; max-height: 100% !important; }
&#13;
&#13;
&#13;

答案 3 :(得分:0)

尝试编写一个function,适用于数组中的一个object。如果这样可行,您可以在for-loop内简单地调用此函数并将其推送到数组或使用Array.map()默认返回array

功能

function createConstructionKit(object) {
    var matarials = object.materials.join('", "') // this will give you for the first case -> wood", "metal", "glass
    var title = object.title // no logic -> just did it to have lesser to write in the next line..
    var capitilizedTitle = title.charAt(0).toUpperCase() + title.slice(1) // capitilize the first one and return all letters off the first index
    return capitilizedTitle + ' has ' + object.materials.length + ' materials: "' + matarials + '"'
}

地图解决方案

var buildingInstructionsdata = data.map(function(object) {
    return createConstructionKit(object)
})

带循环的解决方案

var buildingInstructionsdata = []
for (var i = 0; i < data.length; i++) {
    buildingInstructionsdata.push(createConstructionKit(data[i]))
}

答案 4 :(得分:0)

首先,

console.log(testing);

只是要返回函数的文本,你必须运行这个函数,就像这个

console.log(testing());

这是我的功能,写的是ES6:

var data = [
    {
     "title": "scooter", 
     "materials": ["wood", "metal", "glass"]
    }, 
   {
    "title": "baseball bat", 
    "materials": ["wood", "metal"]
   },
  {
    "title": "coffee table", 
    "materials": ["wood"]
  }];

function newTestingES6() {
  let printStr = '';
  for (let obj of data) { 
    printStr = `${obj.title} has ${obj.materials.length} materials: ${[...obj.materials]}`
    console.log(printStr);      
  }

  return 1;
}

function runTest() {
  console.log(newTestingES6());
}

答案 5 :(得分:0)

这就是我最终开始工作的原因:

 function testing () {
  for (let i = 0; i < data.length; i++) {
   if (data[i].materials.length >2) {
    console.log(`${data[i].title} has ${data[i].materials.length} 
 materials:`);
    for (let j = 0; j < data[i].materials.length; j++) {
     const material = data[i].materials[j];
     console.log("- " + material);
      }
   }
   }
 }
console.log(testing());