简体   繁体   English

地图功能中的if / else语句?

[英]if/else statement in map function?

I am here want to use map function in javascript to loop a type data array,but i get error for these syntax below : 我在这里想在javascript中使用map函数来循环类型数据数组,但是在以下这些语法中出现错误:

function porti(scores) {
const test = scores.map(pass, fail) => {
    if (scores < 75){
      test.fail
    } else {
      test.pass
    }
    return {pass, fail}
  }

}

output must be, if scores < 75 : fail, else : pass 如果分数<75,则输出必须为:失败,否则:通过

console.log(porti([80, 45, 90, 65, 74, 100, 85, 30]));
// { pass: [ 80, 90, 100, 85 ], fail: [ 45, 65, 74, 30 ] }

console.log(porti([]));
// { pass: [], fail: [] }

I think reduce would be better for this situation. 我认为, 减少这种情况会更好。 This will allow us to reduce the array to an object of two item arrays. 这将使我们可以将数组简化为两个项目数组的对象。

 let items = [80, 45, 90, 65, 74, 100, 85, 30] let result = items.reduce((obj, item) => { item < 75 ? obj.fail.push(item) : obj.pass.push(item) return obj }, {pass:[], fail:[]}) console.log(result) 

If you wanted to use filter you could... 如果您想使用过滤器,则可以...

 let items = [80, 45, 90, 65, 74, 100, 85, 30] let result = { pass: items.filter(i => i >= 75), fail: items.filter(i => i < 75) } console.log(result) 

And here is how we can do it with forEach... 这就是我们如何使用forEach ...

 let items = [80, 45, 90, 65, 74, 100, 85, 30] let result = {pass:[], fail:[]} items.forEach(itm => itm < 75 ? result.fail.push(itm) : result.pass.push(itm)) console.log(result) 

You could integrate the check as ternary for getting the key for pushing. 您可以将支票集成为三元以获取推送密钥。

 function porti(scores) { var result = { pass: [], fail: [] }, score; for (score of scores) { result[score < 75 ? 'fail': 'pass'].push(score); } return result } console.log(porti([80, 45, 90, 65, 74, 100, 85, 30])); console.log(porti([])); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

As mentioned above .map() should best be saved for when you are looking to return an array by manipulating a previous array. 如上所述,当您希望通过操作前一个数组返回数组时,最好保存.map()。 If you don't wish to use a vanilla for loop. 如果您不希望使用香草循环。 You could try this 你可以试试这个

const testScores = [...someArray of numbers]
function porti(tesScores) {    
const result = {
   pass: [],
   fail: []
}
    for (let score of testScores) {
        if (score < 75) {
           result.fail.push(score)
         } else {
           result.pass.push(score)
         }
  return result      
}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM