javascript 如何像表中的数字一样用相同的颜色着色?

eyh26e7m  于 2023-02-28  发布在  Java
关注(0)|答案(2)|浏览(162)

我有下面的场景:
1.数字将保持随机和实时变化;
1.这些数字可能具有随机值或相等值 与下一个比较;
我面临什么问题?
我用下面的算法做了一个测试,但是如果你注意到的话,在第2行它插入了"even",这是正确的,因为当前的值和下一个不同,但是,新的值 等于当前值,并插入"odd",但它应该与"even"一起出现,从第11行开始情况相同,但由于它应该在第11行之前为"even",因此第11行和第12行应该为"odd"。

const tst = [
 { buy: 84.16 },
 { buy: 84.16 },
 { buy: 84.15 },
 { buy: 84.15 },
 { buy: 84.15 },
 { buy: 84.15 },
 { buy: 84.15 },
 { buy: 84.15 },
 { buy: 84.15 },
 { buy: 84.15 },
 { buy: 84.15 },
];

let className = [];

tst.forEach((el, i) => {
 const OLD_ELEMENT = tst[i === 0 ? 0 : i - 1].buy;
 className.push(el.buy === OLD_ELEMENT ? 'odd' : 'even');

 console.log(`${el.buy}:${OLD_ELEMENT} --- ${className[i]}`);
})
pqwbnv8z

pqwbnv8z1#

您可以定义一个helper函数来 * 改变 * prev值。
如果值相同,则使用prev,否则调用helper函数

const tst = [{ buy: 84.16 }, { buy: 84.16 }, { buy: 84.15 }, { buy: 84.15 }, { buy: 84.15 }, { buy: 84.15 }, { buy: 84.15 }, { buy: 84.15 }, { buy: 84.15 }, { buy: 84.15 }, { buy: 84.15 } ];
const reversePrev = () => (prev = prev === 'odd' ? 'even' : 'odd');

let prev = 'odd';

tst.forEach((el, i) => {
    const OLD_ELEMENT = tst[i === 0 ? 0 : i - 1].buy;
    const oe = (OLD_ELEMENT === el.buy) ? prev : reversePrev();
    console.log(`${el.buy}:${OLD_ELEMENT} --- ${oe}`);
});
84.16:84.16 --- odd
84.16:84.16 --- odd
84.15:84.16 --- even
84.15:84.15 --- even
84.15:84.15 --- even
84.15:84.15 --- even
84.15:84.15 --- even
84.15:84.15 --- even
84.15:84.15 --- even
84.15:84.15 --- even
84.15:84.15 --- even
vltsax25

vltsax252#

你可以计算变化的次数,然后根据变化次数是奇数还是偶数来选择颜色;比如:

const tst = [ { buy: 84.16 }, { buy: 84.16 }, { buy: 84.15 }, { buy: 84.15 }, { buy: 84.15 }, { buy: 84.15 }, { buy: 84.15 }, { buy: 84.15 }, { buy: 84.15 }, { buy: 84.15 }, { buy: 84.15 }, ];

const with_row_colour = (items, colours = ['light', 'dark']) => {
  let with_colour = [];
  let change_count = 0;
  
  for(const [index, item] of items.entries()) {
    if(items[index - 1]?.buy !== item.buy)
      change_count++;
    
    with_colour.push({ ...item, colour: colours[change_count % 2] });
  }
  
  return with_colour;
};

console.log(with_row_colour(tst));

相关问题