简体   繁体   中英

What does String(num) mean?

I started learning JavaScript a couple of weeks ago.

So I was doing a JavaScript homework where I had to add a hypen between odd numbers. Example: input: 123233 output: 12323-3

I looked around for help, and stumbled on this guy's code

function insertDashes(num) {
 var inStr = String(num);
 var outStr = inStr[0], ii;

for (ii = 1; ii < inStr.length; ii++) 
{
  if (inStr[ii-1] % 2 !== 0 && inStr[ii] % 2 !== 0) {
  outStr += '-';
}

outStr += inStr[ii];
}

return outStr;
}

What does the String(num) in line 2 mean?
Also, why is var outStr = inStr[0], ii; at line 3? I get the inStr[0], but what does the ", ii" do?

What does String(num) mean? In javascript, String() means converting a variable to a string, simply that easy...

Forexample var x=1212323.9; x=String(x);

As you can see, it is the same exact mirror of x.toString() ;
Hope it helps...

String() change something to string example:

num = 7
//7
String(num)
//"7"

Let's look it up at MDN :

The String global object is a constructor for strings, or a sequence of characters.

 String(thing)

Parameters

thing Anything to be converted to a string.

[...] String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (ie, without using the new keyword) are primitive strings.

So it's basically the constructor for the String object, but called without the new keyword so it returns a string literal instead of a String object:

Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of Boolean and Numbers.)

A quick test in the Node console:

> String(123)
'123'
> typeof String(123)
'string'
> new String(123)
[String: '123']
> typeof new String(123)
'object'

In short, it converts an arbitrary data type into string so it can later do string manipulation.


As about this:

var outStr = inStr[0], ii;

... it's just a local variable declaration that defines outStr and ii :

The variable statement declares a variable, optionally initializing it to a value.

 var varname1 [= value1] [, varname2 [= value2] ... [, varnameN [= valueN]]]];

It has the same effect as:

var outStr = inStr[0];
var ii;

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