Javascript - 如何让filter()返回匹配结果

时间:2017-10-02 22:12:14

标签: javascript node.js

我需要将filter的结果返回给forEach。我试过filter但是由于某种原因我似乎无法解决它会导致我的脚本崩溃而没有错误。如果在element.match(/regex/)[1] I log let myAr = ['{"engagement":{"eng_type":"1","eng_src":"2","eng_tid":"100000077777226","eng_data":[]},"coeff2_registry_key":"0406","coeff2_info":"AauUajLpeWuhLBG3jk4ypnhABBcEcbN4M8Z2F6J_CQaQXEhPwL-3j1_dX5vhAleK3K7rjlzqJwnG4xGGaGdFk7Eb","coeff2_action":"1","coeff2_pv_signature":"1509941759"}', '{"engagement":{"eng_type":"1","eng_src":"2","eng_tid":"711427743","eng_data":[]},"coeff2_registry_key":"0406","coeff2_info":"AasHfdsp_Gkdbs3_B4K-_5cN8Y0ZqJPVdm4MYXBzUoXs5QyNoPir8LEYK_RsMpQMxwI","coeff2_action":"1","coeff2_pv_signature":"1509941759"}', '{"engagement":{"eng_type":"1","eng_src":"2","eng_tid":"500890765","eng_data":[]},"coeff2_registry_key":"0406","coeff2_info":"AasBuRKr2vnMecj6ozdELAcZnUPL1FD3ojLSVrYrTckKy_pB2HekM693oJwKD0yH41Y","coeff2_action":"1","coeff2_pv_signature":"1509941759"}', ]; let resultAr = myAr.filter(function(element) { if (element != '#' && element != null) { console.log( element.match(/eng_tid":"(\d*)",/)[1]); // this logs what I want return element.match(/eng_tid":"(\d*)",/)[1]; // this doesn't return what I want } else { return false; } }); console.log(resultAr); 内,它会记录我想要的输出。然而,当我返回时,它返回整个字符串(不仅仅是匹配)。这是代码:

derived

如何在第一个控制台记录器中返回输出内容?

1 个答案:

答案 0 :(得分:1)

您应该使用' map'而不是'过滤'。

let myAr = ['{"engagement":{"eng_type":"1","eng_src":"2","eng_tid":"100000077777226","eng_data":[]},"coeff2_registry_key":"0406","coeff2_info":"AauUajLpeWuhLBG3jk4ypnhABBcEcbN4M8Z2F6J_CQaQXEhPwL-3j1_dX5vhAleK3K7rjlzqJwnG4xGGaGdFk7Eb","coeff2_action":"1","coeff2_pv_signature":"1509941759"}',
    '{"engagement":{"eng_type":"1","eng_src":"2","eng_tid":"711427743","eng_data":[]},"coeff2_registry_key":"0406","coeff2_info":"AasHfdsp_Gkdbs3_B4K-_5cN8Y0ZqJPVdm4MYXBzUoXs5QyNoPir8LEYK_RsMpQMxwI","coeff2_action":"1","coeff2_pv_signature":"1509941759"}',
    '{"engagement":{"eng_type":"1","eng_src":"2","eng_tid":"500890765","eng_data":[]},"coeff2_registry_key":"0406","coeff2_info":"AasBuRKr2vnMecj6ozdELAcZnUPL1FD3ojLSVrYrTckKy_pB2HekM693oJwKD0yH41Y","coeff2_action":"1","coeff2_pv_signature":"1509941759"}',
    ];

let resultAr = myAr.map(function(element) {
    if (element != '#' && element != null) {
        return element.match(/eng_tid":"(\d*)",/)[1];
    } else {
        return false;
    }
});
console.log(resultAr);