简体   繁体   中英

Push value to anonymous array

In my code there is this section :

//config.tls.ca can be a String or and Array of String
if (config.tls.ca && !Array.isArray(config.tls.ca)) 
  config.tls.ca = [].push(config.tls.ca);

I realized that after it : config.tls.ca = 1

Why does this happen ?

 document.write([].push("Hello World")); 

Array.prototype.push returns the new length property of the object upon which the method was called.

You're pushing one item into an empty array, so the new length of the array is 1 , which is returned from push and assigned to .ca . The array itself vanishes into the aether, since it's not assigned to anything.

There's no reason to write such code; you would do this instead:

config.tls.ca = [config.tls.ca];

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