简体   繁体   English

我可以在JavaScript对象中保存条件吗?

[英]Can I save a conditional in a javascript-object?

I'm sorting through an array of objects based on a various conditionals. 我正在根据各种条件对一组对象进行排序。

I want to count each object for the various conditionals and I'm not sure how I should achivie this. 我想为各种条件的每个对象计数,但我不确定该如何实现。 Could I somehow add conditionals to an object: 我可以以某种方式向对象添加条件:

var conversions = [
  {
    name: "Användare",
    conditional: conversion.time_gap > 0,
    count: 0,
  }
]

and then loop through and test them: 然后循环测试它们:

_.each(user.apilog, function(event){
    _.each(conversions, function(conversion){
      if(conversion.conditional){
        conversion.count++;
      }
    })
})

This wont work, because time_gap is a variable inside user.apilog and is not defined, but something like this. 这是行不通的,因为time_gap是user.apilog中的一个变量,并且未定义,但是类似这样。

You could use a function: 您可以使用一个函数:

var conversions = [
  {
    name: "Användare",
    conditional: function(v) { return (v > 0); },
    count: 0,
  }
]

called as: 称为:

_.each(user.apilog, function(event){
   _.each(conversions, function(conversion){
      if(conversion.conditional(time_gap)){
        conversion.count++;
      }
   })
})

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

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