【问题标题】:Object key error key.join is not a function对象键错误 key.join 不是函数
【发布时间】:2017-05-07 16:59:34
【问题描述】:

这段代码有什么问题?我正在努力制作

詹姆斯,3245234545,james@gmail.com

class HelloWorldComponent extends React.Component {
    render() {

        const user = {
            name: "james",
            contact: "3245234545",
            email: "james@gmail.com",
            other: 'dsfsdfsdf'
        };

        return (      
            <div>{user &&
                <div>
                {Object.keys(user).map(key => {

                    if(key === 'name' || key==='contact' || key==='email'){
                        return user[key].join(', ')
                    }

                })}</div>
            }</div>
        )
    }
}

但我得到了错误

user[key].join 不是函数

这是我的 jsbin:http://jsbin.com/kuliwevoku/edit?js,console,output

【问题讨论】:

标签: javascript reactjs ecmascript-6


【解决方案1】:

你应该join map 结果:

Object.keys(user).map(key => {

                if(key === 'name' || key==='contact' || key==='email'){
                    return user[key]
                }

            }).join(', ')

你也可以过滤数组:

   Object.keys(user)
         .filter(key => ['name', 'contact', 'email'].includes(key))
         .map(key => user[key]).join(', ')

【讨论】:

  • 关闭,但这将返回james, 3245234545, james@gmail.com, 。 (注意多余的逗号。)
  • 是的。没想到。
  • key !=="other" 略短... ;)
  • @Jonasw,这个比较短,但是除了other之外可能还有key。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-25
  • 2014-12-26
  • 2013-02-25
  • 1970-01-01
  • 2013-06-15
  • 2014-09-12
  • 2020-12-20
相关资源
最近更新 更多