简体   繁体   English

为什么下面的map函数返回带逗号的字符串?

[英]Why is the following map function returning the strings with commas?

I'm looping through an object. 我正在遍历一个对象。 If one of its keys matches the value of another fields object then return the value of type of that fields object: 如果它的按键彼此的值相匹配fields对象则返回值type的该fields的对象:

// OBJECTS

user: {
  email: '',
  password: ''
}

formFields: [
  { name: 'email', type: 'text', required: true },
  { name: 'password', type: 'password', required: true }
]

// HTML

<input :type="getPropType($key)"

// FUNCTION

getPropType (key) {
  console.log(this.fields)
  console.log(key)
  return this.fields.map(field => {
    if (field.name === key) return field.type
  })
}

It works except a comma is returned with every field.type : 它的工作原理是,每个field.type都返回逗号。

在此处输入图片说明

Which is strange since the logs don't output any commas: 这很奇怪,因为日志不输出任何逗号:

在此处输入图片说明

What could be the cause? 可能是什么原因?

I think what you are trying to do is to extract the type of the object with the same name as the value of key, in that case a more appropriate solution will be to do that exactly that - ie find the element with the given name then extract its type 我认为您要尝试的是提取名称与键值相同的对象的type ,在这种情况下,一种更合适的解决方案是准确地做到这一点-即找到具有给定名称的元素,然后提取其类型

getPropType(key) {
  console.log(this.fields)
  console.log(key);
  var type;
  this.fields.some(field => {
    if (field.name === key) {
      type = field.type;
      return true;
    }
  });
  return type
}

If you want to use .map() , then 如果要使用.map() ,则

return this.fields.filter(field => field.name === key).map(field => field.type).join('')

Array.prototype.map() returns array. Array.prototype.map()返回数组。 Your "getPropType" returned ["text", ""] and it should be reduced in your case. 您的“ getPropType”返回了[“ text”,“”],在您的情况下应该减少它。

return this.fields.map(field => {
    if (field.name === key) return field.type
  }).reduce(function(prev, curr, index, array){return prev + curr});

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

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