use*_*312 86 javascript string numbers
如何在JavaScript中执行以下操作?
将"1","2","3"连接成"123"
将"123"转换为123
添加123 + 100 = 223
隐藏223成"223"
art*_*ung 118
你想熟悉parseInt()和toString().
在您的工具包中有用的是查看变量以找出它是什么类型 - typeof:
<script type="text/javascript">
/**
* print out the value and the type of the variable passed in
*/
function printWithType(val) {
document.write('<pre>');
document.write(val);
document.write(' ');
document.writeln(typeof val);
document.write('</pre>');
}
var a = "1", b = "2", c = "3", result;
// Step (1) Concatenate "1", "2", "3" into "123"
// - concatenation operator is just "+", as long
// as all the items are strings, this works
result = a + b + c;
printWithType(result); //123 string
// - If they were not strings you could do
result = a.toString() + b.toString() + c.toString();
printWithType(result); // 123 string
// Step (2) Convert "123" into 123
result = parseInt(result,10);
printWithType(result); // 123 number
// Step (3) Add 123 + 100 = 223
result = result + 100;
printWithType(result); // 223 number
// Step (4) Convert 223 into "223"
result = result.toString(); //
printWithType(result); // 223 string
// If you concatenate a number with a
// blank string, you get a string
result = result + "";
printWithType(result); //223 string
</script>
Run Code Online (Sandbox Code Playgroud)
Pat*_*ney 50
"1" + "2" + "3"
Run Code Online (Sandbox Code Playgroud)
要么
["1", "2", "3"].join("")
Run Code Online (Sandbox Code Playgroud)
该加入方法串接数组的项转换成字符串,将项目间的指定的分隔符.在这种情况下,"分隔符"是一个空字符串("").
parseInt("123")
Run Code Online (Sandbox Code Playgroud)
在ECMAScript 5之前,有必要传递基数为10的基数:parseInt("123", 10)
123 + 100
Run Code Online (Sandbox Code Playgroud)
(223).toString()
Run Code Online (Sandbox Code Playgroud)
(parseInt("1" + "2" + "3") + 100).toString()
Run Code Online (Sandbox Code Playgroud)
要么
(parseInt(["1", "2", "3"].join("")) + 100).toString()
Run Code Online (Sandbox Code Playgroud)
小智 26
r = ("1"+"2"+"3") // step1 | build string ==> "123"
r = +r // step2 | to number ==> 123
r = r+100 // step3 | +100 ==> 223
r = ""+r // step4 | to string ==> "223"
//in one line
r = ""+(+("1"+"2"+"3")+100);
Run Code Online (Sandbox Code Playgroud)
Nos*_*dna 14
由于JavaScript的打字系统,这些问题一直存在.人们认为他们在得到一个数字的字符串时会得到一个数字.
以下是您可能会看到的一些利用JavaScript处理字符串和数字的方式.就个人而言,我希望JavaScript使用除+之外的一些符号来进行字符串连接.
步骤(1)将"1","2","3"连接成"123"
result = "1" + "2" + "3";
Run Code Online (Sandbox Code Playgroud)
步骤(2)将"123"转换为123
result = +"123";
Run Code Online (Sandbox Code Playgroud)
步骤(3)添加123 + 100 = 223
result = 123 + 100;
Run Code Online (Sandbox Code Playgroud)
步骤(4)将223转换为"223"
result = "" + 223;
Run Code Online (Sandbox Code Playgroud)
如果你知道为什么这些工作,你就不太可能遇到JavaScript表达式的麻烦.
And*_*are 11
你可以这样做:
// step 1
var one = "1" + "2" + "3"; // string value "123"
// step 2
var two = parseInt(one); // integer value 123
// step 3
var three = 123 + 100; // integer value 223
// step 4
var four = three.toString(); // string value "223"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
182111 次 |
| 最近记录: |