融合这2个元素

Fusion this 2 elements

我不知道如何融合我在 ternaire 上尝试过的这两部分代码,但没有成功

if(marge[i].cas_v)
    dps_cote.push({
        x: i,
        label: cote[i].x,
        y: cote[i].y,
        color: 'green',
        indexLabelFontColor : "red",
        indexLabelFontWeight: "bold",
        indexLabel: marge[i].cas_v.toString()
    });
// CAS_V = NULL
else
    dps_cote.push({
        x: i,
        label: cote[i].x,
        y: cote[i].y,
        color: 'green',
        indexLabelFontColor : "red",
        indexLabelFontWeight: "bold",
        indexLabel: ""
    });
let object = {
    x: i,
    label: cote[i].x,
    y: cote[i].y,
    color: 'green',
    indexLabelFontColor : "red",
    indexLabelFontWeight: "bold",
}
if (marge[i].cas_v) {
    object.indexLabel = marge[i].cas_v.toString();
    dps_cote.push(object);
} else {
    dps_cote.push(object);
}

您可以尝试以下方法

dps_cote.push({
        x: i,
        label: cote[i].x,
        y: cote[i].y,
        color: 'green',
        indexLabelFontColor : "red",
        indexLabelFontWeight: "bold",
        indexLabel: marge[i].cas_v?marge[i].cas_v.toString():""
    });

所有值均使用任意值定义,以提供有效的答案。

  1. 先声明and/or定义变量

  2. 然后流量控制像条件语句像if/else if/else and/or三元let x = 0 > y ? z : a

  3. 避免像定义两次的对象那样重写代码,因为 indexLabel 具有两个可能值之一。如果您练习#1,那么重复的代码膨胀将不是问题。

三元与if/else if/else的不同之处在于它就像一个表达式:

let iL = marge[i].cas_v ? marge[i].cas_v.toString() : "";
/* 
if `marge[i].cas_v` exists then `iL` is `marge[i].cas_v.toString()`
otherwise it is `""`
*/
obj.indexLabel = iL;
// whatever `iL` ends up to be -- its assigned to `obj.indexLabel` 

演示

/* 
if i = 0 then indexLabel: "11"
if i = 1 then indexLabel: "121"
if i = 2 then indexLabel: "14641"
*/
let i = 0;
let cote = [{x: 0, y: 0}, {x: 1, y: 0}, {x: 0, y: 1}];
let marge = [{cas_v: 11}, {cas_v: 121}, {cas_v: 14641}];
let dps_cote = [];
let obj = {
  x: i,
  label: cote[i].x,
  y: cote[i].y,
  color: 'green',
  indexLabelFontColor: "red",
  indexLabelFontWeight: "bold",
  indexLabel: ""
};

let iL = marge[i].cas_v ? marge[i].cas_v.toString() : "";

obj.indexLabel = iL;

dps_cote.push(obj);

console.log(dps_cote);