为什么将字符串与生成的字符串进行比较失败

San*_*ing 0 javascript node.js ecmascript-6

谁能解释为什么下面不一样?

const j = 't1'
const t = 1

if (j === ['t'].concat(t)) {
  console.log('the same')
}
Run Code Online (Sandbox Code Playgroud)

我原以为我会t1与比较t1,但我想我不是?

Cha*_*lie 5

您正在使用Array.prototype.concat返回数组的方法。

['t'].concat(t);  //["t", 1]
Run Code Online (Sandbox Code Playgroud)

这不等于值或类型 't1'

但是,如果您使用了String.prototype.concat,您将获得预期的结果。

't'.concat('1'); //"t1"
Run Code Online (Sandbox Code Playgroud)

  • 绝对精确的话是 `["t", 1]` :) (3认同)