如果在推/非移动javascript中的条件

时间:2016-03-31 08:47:46

标签: javascript jquery

我有这个javascript对象。

infoHolder.labels.push({
 label: 'testLabel',
 image: 'testImage',

 // Condition - Not working!
 if(true) {
 toString: function() { return this.label;}
 } else {
  toString: function() { return this.image;}
 }; 
});

当我然后插入数据时,我希望在我的推送中有一个条件。如:

   $("#Search").on("click", function () {
    var $opt = $("#StartStation option:selected"); //From: Selected     
    var strno =parseInt(  $opt.val()); //New Integer Start value of fare

    var $opt2 = $("#EndStation option:selected"); //To: Selected
    var endno = parseInt($opt2.val()); //New Integer End value of fare

    // Fare Calculation -----------------------------------------------------

    if (strno > endno) { // If the selected station start from South e.g Taft-North
        var fare = (strno - endno);
    }
    else {
        var fare = (endno - strno);
    }
    console.log(fare);
    if (fare >= 1 && fare <= 2) {
        var fareresult = "$13";
    }
    else if (fare >= 3 && fare <= 4) {
        var fareresult = "$16";
    }
    else if (fare >= 5 && fare <= 7) {
        var fareresult = "$20";
    }

    else if (fare >= 8 && fare <= 10) {
        var fareresult = "$24";
    }
    else if (fare >= 11 && fare <= 12) {
        var fareresult = "$28";
    }

    $("#FareOutput").html("Fare:" + " " + fareresult);

});

有一个简单的解决方案吗? 小提琴https://jsfiddle.net/dvy10ms7/2/

3 个答案:

答案 0 :(得分:1)

我可以看到你可以使用的两个选项,取决于条件本身:

toString: condition ? function() { return this.label } : function() { return this.image }

......或......

type: condition ? "label" : "image",
toString: function() { return this[this.type] }

答案 1 :(得分:1)

也许是这些方面的东西:

var infoHolder = { labels: [] }

infoHolder.labels.push({
    label: 'testlabel',
    get image() {return true ? 'testImage' : 'somethingElse'},
    toString: function() {return this.label}
})

infoHolder.labels.forEach(function(d){ console.log(d.image) })

查看prop getters

甚至更有趣的是创建new / extend [].push

function pushTo(target, condition, props){
    // add protection here  
    Array.prototype.push.call(target, condition ? props["label"] : props["image"])
    return target
}

var o = pushTo(infoHolder.labels, 1 == "1", {label: "testLabel", image: "testImage"})

console.log(o)

答案 2 :(得分:0)

我不确定,但似乎你想要这样的东西:

var infoHolder = {
  labels: [],
};

infoHolder.labels.push({
  label: 'testlabel',
  image: function() {
    return true ? 'testImage' : 'somethingElse';
  },
  toString: function() {
    return this.label;
  }
});
console.log(infoHolder);
document.querySelector('pre').innerHTML = infoHolder.labels[0].image() + ' <--image() :: toString() --> '+infoHolder.labels[0].toString();
<pre></pre>