问题
myCoolObject {
a: 0
b: 12
c: 24
}
I want to concatenate a
, b
and c
so that they look like a unique string "a-b-c" (or "0-12-24" in the example).
a
, b
and c
will 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?
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?
回答1:
var myCoolString = myCoolObject.a + '-' + myCoolObject.b + '-' + myCoolObject.c;
EDIT:
With ES6, you can use template strings to interpolate numbers into strings:
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);
回答2:
how can I do this in JS without [...] writing too much code?
If you know all of your numbers are positive, you can write even less code to achieve the same as we know JavaScript executes left-to-right.
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.
'AK' + -47 // "AK-47"
回答3:
Try sprintf() for JavaScript.
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)
回答4:
Without much code it looks perfect here is the demo
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));
回答5:
This is mostly done with 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()
:
format = function(fmt /*, args */) {
var args = [].slice.call(arguments, 1);
return fmt.replace(/{(\d+)}/g, function($0, $1) {
return String(args[$1])
})
}
and then:
var pickedDate = format('{0}-{1}-{2}',
this.getSelectedDay().year,
this.getSelectedDay().month,
this.getSelectedDay().day)
来源:https://stackoverflow.com/questions/16965780/concatenating-numbers-as-string-in-javascript