简体   繁体   中英

What is a good way to emulate casting?

From underscoresjs.org

  // Generate a unique integer id (unique within the entire client session).
  // Useful for temporary DOM ids.
  var idCounter = 0;
  _.uniqueId = function(prefix) {
    var id = ++idCounter + '';
    return prefix ? prefix + id : id;
  };

It appears that this line:

var id = ++idCounter + '';

casts a number to a string by concatenating it with the empty string.

Is this a good way to cast from a number to a string?

Yes, it's a good way to cast to a string.

If you want something more explicit, use .toString() .

var id = (++idCounter).toString();

As long as Number.prototype.toString() has not been overwritten, this will work.

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