首页 > 解决方案 > 为什么我的 console.log(variable) 显示两个不同的值?

问题描述

在此处输入图像描述我正在做一个算法。设置两个 rgb 颜色之间的距离,但它返回了错误的值,为什么?

  let tests = [[128, 0, 0], [170, 110, 40], [128, 128, 0], [0, 128, 128], [0, 0, 128],
    [0, 0, 0], [230, 25, 75], [245, 130, 48], [255, 225, 25], [210, 245, 60], [60, 180, 75],
    [70, 240, 240], [0, 130, 200], [145, 30, 180], [240, 50, 230], [128, 128, 128], [250, 190, 190],
    [255, 215, 180], [255, 250, 200], [170, 255, 195], [230, 190, 255], [255, 255, 255]]
  let corFinal = [0, 0, 0]
  let coresFinais = []
  let menorDist = 256
  getPaletteFromURL(this.imageTest, 8, 1).then((response) => {
    console.log('array de cores', response)
    response.forEach((color) => {
      tests.forEach((test) => {
        let dist = Math.sqrt(Math.pow(test[0] - color[0], 2) + Math.pow(test[1] - color[1], 2) + Math.pow(test[2] - color[2], 2))
        if (dist < menorDist) {
          menorDist = dist
          corFinal[0] = test[0]
          corFinal[1] = test[1]
          corFinal[2] = test[2]
          console.log(corFinal)
        }
      })
      console.log(corFinal)
      menorDist = 256
      coresFinais.push(corFinal)
    })
    console.log('array final', coresFinais)
  })

响应是与“测试”样式相同的数组数组

运行 console.log(test[0]) 确实显示了正确的值。console.log(corFinal) 确实显示了两个值

标签: javascriptarraysbrowserconsole

解决方案


实际上,错误是我正在逐字段更新数组(我不知道为什么返回错误值)。

所以我改为:

corFinal = test

然后代码起作用了。


推荐阅读