【问题标题】:problem with making a string using values of object properties使用对象属性的值制作字符串的问题
【发布时间】:2019-07-02 07:43:42
【问题描述】:

我在创建包含使用现有属性值的字符串的新属性时遇到问题。你能告诉我为什么我不能让它工作吗?

 function greetDevelopers(list) {
  for(let i=0 ; i< list.length ; i++ ){
  return 'Hi '+list[i].firstName +', what do you like the most about 
 '+list[i].language +'?'
  }
 }

当我编写这样的代码向每个对象输入新属性时,它会一直显示第一个对象结果。

但是,如果我尝试一下

 function greetDevelopers(list) {
  for(let i=0 ; i< list.length ; i++ ){
  return 'Hi '+list[1].firstName +', what do you like the most about 
 '+list[1].language +'?'
  }
 }

它在对象中显示正确的值。

https://www.codewars.com/kata/coding-meetup-number-2-higher-order-functions-series-greet-developers/train/javascript

您的任务是返回一个数组,其中每个对象都有一个新属性“greeting”,其字符串值如下:

你好,你最喜欢的什么?

function greetDevelopers(list) {
 for(let i=0 ; i< list.length ; i++ ){
 return 'Hi '+list[i].firstName +', what do you like the most about 
'+list[i].language +'?'
 }
}

var list1 = [
  { firstName: 'Sofia', lastName: 'I.', country: 'Argentina', continent: 
'Americas', age: 35, language: 'Java' },
  { firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 
'Europe', age: 35, language: 'Python' },
  { firstName: 'Madison', lastName: 'U.', country: 'United States', 
continent: 'Americas', age: 32, language: 'Ruby' } 
];
Test.assertDeepEquals(greetDevelopers(list1), answer);

[
  { firstName: 'Sofia', lastName: 'I.', country: 'Argentina', continent: 
'Americas', age: 35, language: 'Java',
    greeting: 'Hi Sofia, what do you like the most about Java?'
  },
  { firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 
'Europe', age: 35, language: 'Python',
    greeting: 'Hi Lukas, what do you like the most about Python?'
  },
  { firstName: 'Madison', lastName: 'U.', country: 'United States', 
continent: 'Americas', age: 32, language: 'Ruby',
    greeting: 'Hi Madison, what do you like the most about Ruby?'
  } 
];

我想变成这样。但我的代码不起作用。你能帮忙吗? 谢谢!

【问题讨论】:

  • 为什么你开始一个for 循环,但在第一次迭代中返回?

标签: javascript arrays object javascript-objects


【解决方案1】:

当您需要从另一个数组创建一个数组时,您通常可以使用map 函数来完成。 map 函数获取一个数组的每个条目并返回一个新数组。对于你的情况,我会这样做:

const list1 = [
  { firstName: 'Sofia', lastName: 'I.', country: 'Argentina', continent: 
'Americas', age: 35, language: 'Java',
    //greeting: 'Hi Sofia, what do you like the most about Java?'
  },
  { firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 
'Europe', age: 35, language: 'Python',
    //greeting: 'Hi Lukas, what do you like the most about Python?'
  },
  { firstName: 'Madison', lastName: 'U.', country: 'United States', 
continent: 'Americas', age: 32, language: 'Ruby',
    //greeting: 'Hi Madison, what do you like the most about Ruby?'
  } 
];

const greetDevelopers = list1.map((item) => {
    return `Hi ${item.firstName}, what do you like the most about ${item.language}?`
});

console.log(greetDevelopers);

或者,如果您真的想将属性添加到现有对象:

let list1 = [
  { firstName: 'Sofia', lastName: 'I.', country: 'Argentina', continent: 
'Americas', age: 35, language: 'Java',
    // greeting: 'Hi Sofia, what do you like the most about Java?'
  },
  { firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 
'Europe', age: 35, language: 'Python',
    // greeting: 'Hi Lukas, what do you like the most about Python?'
  },
  { firstName: 'Madison', lastName: 'U.', country: 'United States', 
continent: 'Americas', age: 32, language: 'Ruby',
    // greeting: 'Hi Madison, what do you like the most about Ruby?'
  } 
];

list1.forEach((item) => {
    item.greeting = `Hi ${item.firstName}, what do you like the most about ${item.language}?`
});

console.log(list1);

【讨论】:

  • 我还没有学过map,但我会学习它并尝试用这个解决问题!谢谢!
  • 当您想为数组中的每个条目应用某些内容时,映射通常很有用。它返回一个新数组。例如,当您要呈现数据时,它非常有用:如果您有一个字符串数组,并且您希望将每个字符串包装在一个文本组件中。使用地图,您只需: const texts = data.map(item=>(item))。但我认为在您的情况下,您不想创建数组的副本,而只是修改它的每个条目。您应该使用 forEach,它遍历每个条目(因此您可以直接更改它),但不返回新数组。
  • 非常感谢大卫。学过地图,真的很有用!
【解决方案2】:

你需要在 for 循环中调用你的函数。您正在返回列表的第一个结果,而不是给它循环的机会。

function greetDevelopers(developer) {
    return 'Hi '+developer.firstName +', what do you like the most about '+developer.language +'?'
 }

for(let i=0 ; i< list.length ; i++ ){
  greetDevelopers(list[i]);
}

【讨论】:

    【解决方案3】:

    您正在返回循环内的字符串。每当你返回时,你的意思是说你想停止一切并返回给定的值,这很好,例如,如果你在循环中搜索特定元素然后你找到了它,因为它没有意义完成循环。

    但是,在我看来,您的意思是为每个用户返回一个字符串

    为此,您可以执行以下操作:

    function greetDevelopers(list) {
      let greetings = new Array();
      for(let i=0 ; i< list.length ; i++ ){
        greetings.push('Hi '+list[i].firstName +', what do you like the most about '+list[i].language +'?');
      }
      return greetings;
    }
    
    console.log(greetDevelopers([{firstName: 'Jon', language: 'Java'}, {firstName: 'Peter', language: 'English'}]));

    或者,在更多高级浏览器中,您还可以执行以下操作,从而为您提供更可控的基于迭代器的方法:

        function* greetDevelopers(list) {
          for(let i=0 ; i< list.length ; i++ ){
            yield 'Hi '+list[i].firstName +', what do you like the most about '+list[i].language +'?';
          }
        }
    
    const greetingsIterator = greetDevelopers([{firstName: 'Jon', language: 'Java'}, {firstName: 'Peter', language: 'English'}]);
    
    console.log(greetingsIterator.next().value);
    console.log(greetingsIterator.next().value);

    更多关于产量和迭代器协议的细节可以在here找到。

    【讨论】:

    • 非常感谢您的建议和链接!
    【解决方案4】:

    您需要使用您正在构造的字符串为list 中的每个对象添加greeting 属性。

    function greetDevelopers(list) {
      for (let i = 0; i < list.length; i++) {
        list[i].greeting = 'Hi ' + list[i].firstName + ', what do you like the most about ' + list[i].language + ' ? ';
      }
      return list;
    }
    
    var list1 = [{firstName:'Sofia',lastName:'I.',country:'Argentina',continent:'Americas',age:35,language:'Java'},{firstName:'Lukas',lastName:'X.',country:'Croatia',continent:'Europe',age:35,language:'Python'},{firstName:'Madison',lastName:'U.',country:'United States',continent:'Americas',age:32,language:'Ruby'}]
    
    console.log(greetDevelopers(list1));
    .as-console-wrapper { max-height: 100% !important; top: auto; }

    【讨论】:

      【解决方案5】:

      您可以使用Array#map 返回一个对象数组,其中destructuring assignment 用于firstNamelanguagetemplate literal 用于具有变化值的所需字符串。

      function greetDevelopers(list) {
          return list.map(({ firstName, language }) =>
              ({ geeting: `Hi ${firstName}, what do you like the most about ${language}?` }));
      }
      
      var list1 = [{ firstName: 'Sofia', lastName: 'I.', country: 'Argentina', continent: 'Americas', age: 35, language: 'Java' }, { firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 35, language: 'Python' }, { firstName: 'Madison', lastName: 'U.', country: 'United States', continent: 'Americas', age: 32, language: 'Ruby' }];
      
      console.log(greetDevelopers(list1));

      【讨论】:

      • 我还没学过地图。我猜 map 可以在每个对象中输入新属性。我会更多地学习并尝试这种方式。似乎容易多了!非常感谢。
      猜你喜欢
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 2012-07-05
      • 1970-01-01
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      相关资源
      最近更新 更多