简体   繁体   中英

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

Why With the below declaration and assignment

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

is this allowed and will give [1,2,3,4,5] "Jello"

console.log(num + "Jello");

But with the below declaration and assignment

const num = { Flavour: "Apple" };

This will not give you Apple "Jello"

console.log(num + "Jello");

(Note: the below links to pages on MDN, which started out as the documentation for the JS in Mozilla browsers, but applies beyond that these days.)

Firstly, for a + b to return a sensible result, a and b should be of the same type. If they're different types, they must becoerced to the same type (see also ECMAScript 2021, section 7.1 "Type Conversion" ).

Furthermore, the 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 is a little more involved, and takes into account primitives, such as null , that don't have a toString method).

For arrays, 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 , and has the form `[object ${Tag}]` , where Tag is a string representing the builtin type of the object.

To get a string containing a representation of an object, you need to use something like JSON.stringify :

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

If you just want the values, and the object is flat (ie no values are themselves objects), you can use Object.values :

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

If you want to join the values with something other than a comma, explicitly call join with the separator:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM