繁体   English   中英

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

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

我正在遍历一个对象。 如果它的按键彼此的值相匹配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
  })
}

它的工作原理是,每个field.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
}

如果要使用.map() ,则

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

Array.prototype.map()返回数组。 您的“ 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