我希望能够检查并查看哪些键以字母“gra”开头,并且仅返回该内容。我用下面的代码尝试了一些事情。在一种方法中,我在返回 html 中添加了类似 {key.match(/gra/g)} 的内容,但它不是很有效(并且仍然输出空白内容)。我也尝试过添加这样的内容:
if(String(this.props.profile[key]).match(/gra/g)))
也尝试过:
if(this.props.profile[key].match(/gra/g))
但不断收到“.match”不是函数或无法读取未定义等错误。我尝试了各种其他方法,但似乎无法使其正常工作。
var grapes = Object.keys(this.props.profile).map(function(key) {
if(this.props.profile[key] !=null) {
return (
<li key={key} className="example-class">
<label>{key}:</label>{ this.props.profile[key] }
</li>
);
}
}, this);
<html>
{grapes}
</html>
那么,综上所述,使用正则表达式过滤此类内容的最佳方法是什么?
最佳答案
为什么不直接过滤数组
var grapes = Object.keys(this.props.profile)
.filter(function(key) {
return key && key.toLowerCase().indexOf('gra') === 0;
})
.map(function(key) {
return (
<li key={key} className="example-class">
<label>{key}:</label>{ this.props.profile[key] }
</li>
);
}, this);
关于javascript - 在 React.js 中使用正则表达式过滤数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34949789/