将字符串作为数组前缀与将字符串作为对象数组前缀 - React/JS

Prefixing a String to an array vs Prefixing a string to an array of objects - React/JS

为什么使用下面的声明和赋值

const num = [1,2,3,4,5];

这是否允许,并且会给出 [1,2,3,4,5]“Jello”

console.log(num + "Jello");

但是使用下面的声明和赋值

const num = { Flavour: "Apple" };

这个不会给你苹果“果冻”

console.log(num + "Jello");

(注意:以下链接指向 MDN 上的页面,这些页面最初是作为 Mozilla 浏览器中 JS 的文档,但现在适用于更多内容。)

首先,对于a + b到return一个合理的结果,ab应该是同一类型。如果它们是不同的类型,它们必须是 coerced to the same type (see also ECMAScript 2021, section 7.1 "Type Conversion").

此外,addition operator only works on two types: numbers and strings (see also ECMAScript 2021, section 13.8 "Additive Operators"). Basically, if the operands aren't both numbers, then they're coerced to strings basically by calling their toString() methods (the exact process 稍微复杂一点,它考虑了没有 toString 方法的原语,例如 null

对于数组,Array.prototype.toString will call toString() on each element and join the results with a comma (the meat of it is defined in the specification for Array.prototype.join). The more general Object.prototype.toString will, for an object literal, return simply '[object Object]'. This value is comes from the specification for Object.prototype.toString,并且具有 `[object ${Tag}]` 的形式,其中 Tag 是表示对象内置类型的字符串。

要获取包含对象表示的字符串,您需要使用类似 JSON.stringify:

的方法
JSON.stringify({ Flavour: "Apple" }) + ' Jello'

如果你只想要值,并且对象是平面的(即没有值本身就是对象),你可以使用 Object.values:

Object.values({ Cost: "Cheap", Flavour: "Apple" }) + 'Jello'

如果您想用逗号以外的东西连接值,请使用分隔符显式调用 join

Object.values({ Cost: "Cheap", Flavour: "Apple" }).join(' ') + ' Jello'