javascript 在Javascript中将数字连接为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16965780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:37:33  来源:igfitidea点击:

Concatenating numbers as string in Javascript

javascriptstring-concatenation

提问by Saturnix

myCoolObject {
  a: 0
  b: 12
  c: 24
}

I want to concatenate a, band cso that they look like a unique string "a-b-c" (or "0-12-24" in the example).

我想连接abc让他们看起来像一个唯一的字符串“ABC”(或如“0-12-24”)。

a, band cwill always represent numbers. Converting each one of them from int to string require a lot of code: I'd just use sprintf()if I were in PHP or C, but how can I do this in JS without using toString()for each parameter and writing too much code?

a,b并且c总是代表数字。将它们中的每一个从 int 转换为 string 需要大量代码:sprintf()如果我在 PHP 或 C 中,我只会使用,但是如何在 JS 中执行此操作而不使用toString()每个参数并编写太多代码?

Whole code:

全码:

var pickedDate = this.getSelectedDay().year.toString() + "-" + this.getSelectedDay().month.toString() + this.getSelectedDay().day.toString();

Seriously? Isn't there any more efficient way of doing this in js?

严重地?在 js 中没有更有效的方法吗?

回答by rink.attendant.6

var myCoolString = myCoolObject.a + '-' + myCoolObject.b + '-' + myCoolObject.c;

EDIT:

编辑:

With ES6, you can use template stringsto interpolate numbers into strings:

使用 ES6,您可以使用模板字符串将数字插入到字符串中:

let myCoolString = `${myCoolObject.a}-${myCoolObject.b}-${myCoolObject.c}`;

Try it:

试试看:

var myCoolObject = {
  a: 0,
  b: 12,
  c: 24
};

var myCoolString = myCoolObject.a + '-' + myCoolObject.b + '-' + myCoolObject.c;

console.log(typeof myCoolString);
console.log(myCoolString);

回答by Paul S.

how can I do this in JS without [...] writing too much code?

我怎样才能在 JS 中做到这一点而不 [...] 编写太多代码?

If you know all of your numbers are positive, you can write even less code to achieve the same as we know JavaScriptexecutes left-to-right.

如果您知道所有数字都是正数,那么您可以编写更少的代码来实现我们所知道的JavaScript从左到右执行的相同效果。

var obj = {a: 0, b: 12, c: 24}; /* define object
String + Number = String
                  String + Number = String
                                    String + Number = String
String + Number + Number + Number     = String    */
  ''   +  obj.a + -obj.b + -obj.c; // = "0-12-24"

The -were inserted because String + -Number = "String-Number", e.g.

-插入,因为String + -Number = "String-Number",如

'AK' + -47 // "AK-47"

回答by georg

This is mostly done with Array.join:

这主要是通过以下方式完成的Array.join

var pickedDate = [
    this.getSelectedDay().year, 
    this.getSelectedDay().month, 
    this.getSelectedDay().day
].join("-")

Although I personally prefer a small utility function similar to pythonic format():

虽然我个人更喜欢类似于 pythonic 的小实用函数format()

format = function(fmt /*, args */) {
    var args = [].slice.call(arguments, 1);
    return fmt.replace(/{(\d+)}/g, function(
var pickedDate = format('{0}-{1}-{2}', 
    this.getSelectedDay().year, 
    this.getSelectedDay().month, 
    this.getSelectedDay().day)
, ) { return String(args[]) }) }

and then:

接着:

myObj = {
  a: 0,
  b: 12,
  c: 24
}; 

var r="";

// iterate through all object properties
for (var p in myObj) 
{
    //concatenate it
    r+=myObj[p]+"-";
}

//remove the last dash
r=r.substring(0,r.length-1);

alert(r.substring(0,r.length-1));

回答by Nikola Mitev

Without much code it looks perfect here is the demo

没有太多代码它看起来很完美这里是演示

if (!String.prototype.format) {
String.prototype.format = function() {
   var args = arguments;
   return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
       ? args[number]
        : match
      ;
   });
  };
}

"{0} - {1} - {2}".format(myCoolObject.a, myCoolObject.b,myCoolObject.c)

回答by Igor S.

  1. Try sprintf()for JavaScript.

  2. Add new method to string

    if (!String.prototype.format) {
    String.prototype.format = function() {
       var args = arguments;
       return this.replace(/{(\d+)}/g, function(match, number) { 
          return typeof args[number] != 'undefined'
           ? args[number]
            : match
          ;
       });
      };
    }
    
    "{0} - {1} - {2}".format(myCoolObject.a, myCoolObject.b,myCoolObject.c)
    
  1. 为 JavaScript尝试sprintf()

  2. 向字符串添加新方法

    ##代码##