简体   繁体   English

如果其他条件在推/不转移的JavaScript

[英]if else condition in push/unshift javascript

I have this javascript Object. 我有这个javascript对象。

var infoHolder = {
 labels: [],
};

When i then insert data, i would like to have a condition in my push. 当我随后插入数据时,我想在条件中添加条件。 such as: 如:

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

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

Is there a simple solution to this ? 有一个简单的解决方案吗? fiddle https://jsfiddle.net/t9wqeakL/ 小提琴https://jsfiddle.net/t9wqeakL/

I can see two options You may use, depends on the condition itself: 我可以看到两个可以使用的选项,具体取决于条件本身:

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

... or ... ... 要么 ...

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

Maybe something along these lines: 也许遵循以下思路:

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) })

Check out prop getters . 检查吸气剂

Or even more interesting create new/extend [].push : 甚至更有趣的是创建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)

I am not sure but it seems you want something like this: 我不确定,但看来您想要这样的东西:

 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> 

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

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