如何在第三个变量中从2个单独的变量分配结果



这里很琐碎的问题。无法弄清楚。
我正在尝试从primaryWorksecondaryWork获得结果,并将这些结果分配给变量myWorkList。请让我知道我在这里做错了什么。

谢谢

  let myWorkList
  let primaryWork = this.list.filter(r => r.worker === null)
  let secondaryWork = this.list.filter(r => r.worker === this.currentWorker.id)
  if (this.list) {
    if (this.superuser && this.currentWorker) myWorkList = primaryWork && secondaryWork
  }
  return myWorkList

听起来primaryWorksecondaryWork都是数组。您可能正在寻找.concat()方法:

  let myWorkList
  let primaryWork = this.list.filter(r => r.worker === null)
  let secondaryWork = this.list.filter(r => r.worker === this.currentWorker.id)
  if (this.list) {
    if (this.superuser && this.currentWorker) myWorkList = primaryWork.concat(secondaryWork)
  }
  return myWorkList

或修复代码中的一些潜在错误:

  // whoever is using the return value from this function expects an array, so if this.list is undefined (or if this.superuser is false) we should return an empty array instead of undefined
  let myWorkList = []
  // if this.list is undefined, this.list.filter will fail - so we do it inside the conditional block
  if (this.list) {
    let primaryWork = [];
    let secondaryWork = [];
    // if this.superuser or this.currentWorker are false, we don't need to waste CPU cycles computing this.list.filter()
    if (this.superuser)
      // I made the assumption (correct me if I'm wrong) that if r.worker is null, the work belongs to the superuser
      primaryWork = this.list.filter(r => r.worker === null)
    // if this.currentWorker is undefined, this.currentWorker.id will fail -- so we perform this filter inside yet another conditional block
    if (this.currentWorker)
      secondaryWork = this.list.filter(r => r.worker === this.currentWorker.id)
    myWorkList = primaryWork.concat(secondaryWork)
  }
  return myWorkList

最后,您可以将所有这些将所有内容串入单个filter中,并且只能在列表上迭代一次,而不是两次,例如:

  return (
    // Check that this.list is defined before filtering
    this.list ?
      this.list.filter(r =>
        // superuser case
        (this.superuser && r.worker === null)
        || // or
        // non-superuser case
        (this.currentWorker && r.worker === this.currentWorker.id)
      )
    // Return an empty array if this.list was undefined
    : []
  );

请注意,在此最终版本中,我们不实例化myWorkListprimaryWork secondaryWork。如果我们可以直接返回所需的最终值,我们就不需要在内存中分配空数组来垃圾收集它们。最终表格应更快地运行2-3次:

  • 速度是两倍,因为我们迭代this.list数组一次,而不是两次
  • 比这更快的一点,因为我们避免了不必要的内存分配

初步基准在我的机器上将其固定在约2.4个:

var list = [{worker: null}, {worker: null}, {worker: 1}, {worker: 2}, {worker: 2}, {worker: 3}, {worker: 4}, {worker: null}, {worker: 2}]
var d0 = new Date(); for (var i = 0; i < 500000; i++) { var primary = list.filter(r => r.worker === null); var secondary = list.filter(r => r.worker === 2); primary.concat(secondary); } console.log(new Date() - d0);
// 659
var d0 = new Date(); for (var i = 0; i < 500000; i++) { list.filter(r => r.worker === null || r.worker === 2); } console.log(new Date() - d0);
// 272

最新更新