简体   繁体   English

如何避免 javascript 中的代码重复?

[英]How to avoid repetition of code in javascript?

I'm writing a node program where I input an id (required) and an attribute (optional) and the function iterates through an array of objects until it finds an object that has the same input id and/or attribute.我正在编写一个节点程序,在其中输入一个 id(必需)和一个属性(可选),并且 function 遍历对象数组,直到找到具有相同输入 id 和/或属性的 object。

So far I have this and it works:到目前为止,我有这个并且它有效:

       if(id && query === undefined){
       let searchById = employeesObj.filter(employee => {
           return employee.id == id
       }) 
       if(Object.entries(searchById).length === 0){
           console.log('This employee doesn\'t exist')
           return
    }
    console.log('Employee information: \n', searchById)
    } 

    if(query){
        let searchById = employeesObj.filter(employee => {
            return employee.id == id
        })
        if(Object.entries(searchById).length === 0){
            console.log('This employee doesn\'t exist')
            return}
        let obj = searchById[0]
        if(obj.hasOwnProperty(query)){
            console.log(obj[query])
        }else{
        console.log('input query doesn\'t exist')
    }
    } 

})

As you can see, this part of the functions is the same:可以看到,这部分功能是一样的:

let searchById = employeesObj.filter(employee => {
       return employee.id == id
   }) 
   if(Object.entries(searchById).length === 0){
       console.log('This employee doesn\'t exist')
       return
}

In one it searches when you input an id and in other when you input a query(attribute).一种是在您输入 id 时进行搜索,另一种是在您输入查询(属性)时进行搜索。

How can I avoid repetition in my code?如何避免代码中的重复?

In general, if you have to run code more than once, you put it into a function.通常,如果您必须多次运行代码,则将其放入 function 中。 However, a better way to fix code repetition is to avoid repeating the thing in the first place.但是,修复代码重复的更好方法是首先避免重复该事情。 You can do that here by doing the ID search at the beginning, only once, and keeping the searchById result around for when you check for the query:您可以通过在开始时仅执行一次 ID 搜索来执行此操作,并在检查查询时保留searchById结果:

let searchById = employeesObj.filter(employee => {
    return employee.id == id
}) 
if(Object.entries(searchById).length === 0){
    console.log('This employee doesn\'t exist')
    return
}


if(query){
    let obj = searchById[0]
    if(obj.hasOwnProperty(query)){
        console.log(obj[query])
    } else {
        console.log('input query doesn\'t exist')
    }
} else {
    console.log('Employee information: \n', searchById)
}

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

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