如何在javascript中使用map函数而不是for循环?

时间:2017-12-06 05:31:51

标签: javascript arrays nodes

这是我的阵列:

var filteredData = [{ id: 1, phoneno: '91888888888', sender: 'test' },{ id: 2, phoneno: '9199999999999', sender: 'hel' }]

我用于循环

for (var i = 0; i < filteredData.length; i++) {
   if (filteredData[i].sender === test) {
       console.log('worked');
   }else{
       console.log('not worked');
   }
}

如何使用地图做到这一点?在javascript而不是for循环。

4 个答案:

答案 0 :(得分:6)

正如评论中所提到的,forEach最好在您的示例中使用。但是,如果您坚持使用map,只需将forEach替换为map,代码仍然可以使用。

var filteredData = [{ id: 1, phoneno: '918888888888', sender: 'test' },{ id: 2, phoneno: '918888888888', sender: 'hel' }];

filteredData.forEach(function(item){
   if (item.sender === test) {
       console.log('worked');
   }
   else {
       console.log('not worked');
   }
});

答案 1 :(得分:0)

filteredData.map(value => {
    if (value.sender === test) {
        console.log("worked");
    } else {
        console.log('not worked');
    }
});

答案 2 :(得分:-1)

使用underscore.js,

var filteredData = [{ id: 1, phoneno: '917418306474', sender: 'test' },{ id: 2, phoneno: '917338966917', sender: 'hel' }];

 _.map(filteredData, function(data){
   if (data.sender === test) {
    console.log('worked');
   }else {
    console.log('not worked');}
});

答案 3 :(得分:-2)

var filteredData = [{ id: 1, phoneno: '77777777777', sender: 'test' },{ id: 2, phoneno: '917338966917', sender: 'hel' }]
filteredData.map(filterDetails); 
function filterDetails(data) {  
    if(data.sender == 'test'){
     console.log('worked');
     }
     else{
     console.log('not worked');
     }
}