这是一个 typescript 方法,它想要遍历一个字符串数组,并返回另一个字符串数组,其中,匹配正则表达式的字符串(格式类似于“[la la la]”的字符串将变成“la la la”和不匹配的字符串被丢弃。所以如果我的输入数组是:
"[x]", "x", "[y]"
变成
"x", "y"
这是我的代码:
questions(): string[] {
var regexp = /\[(.*)\]/;
return this.rawRecords[0].map((value) => {
console.log(value);
var match = regexp.exec(value);
if (match) {
return match[1];
}
});
}
我最终得到这样的输出:
"x", undefined, "y"
因为“如果(匹配)”。编写此代码的正确 typescript /javascript 方法是什么?
最佳答案
只需过滤
它们:
return this.rawRecords[0].map((value) => {
console.log(value);
var match = regexp.exec(value);
if (match) {
return match[1];
}
});
}).filter(x=>!!x);
关于javascript - Typescript 数组映射 vs 过滤器 vs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31174085/