toString() 不像以前那样工作

问题描述 投票:0回答:3

我有一个问题。 我有一个代码,例如:

var g = "192"; //Global defined//

function g(){

    if (g<200){

        g.toString();
        console.log(typeof(g));
        g++;
        window.setTimeout("rgb()", 3000);

    } else {

        return;
    }}
$(g);

我运行这段代码,首先它会返回“String”。但在第二次运行时,它返回“数字”。为什么?在函数本身中有 g.toString() 方法。为什么跑完一圈就变成数字了?

感谢您的回答!

javascript string function tostring
3个回答
0
投票

您需要将 toString 分配给您的变量,并为您的函数或变量使用不同的名称,如下所示:

var g = "192"; //Global defined//

function test() {

    if (g < 195) {

        g = g.toString();
        console.log(typeof (g));
        g++;
    } else {

        return;
    }
}
test();

看到这个小提琴


0
投票

值和函数同名,
g
。你需要保存新值:

var g = "192" //de Global value

function green(){
    g = g.parseInt(g); //de Make sure it's a string.
    if (g<200){
        console.log(typeof(g));
        g++;
        g = g.toString(); //de Make it a string again.
        window.setTimeout("rgb()", 3000);

    } else {

        return;
    }
}

console.log( green() );
  1. 您需要为变量和函数选择不同的名称。
  2. 您需要手动存储和更改您的变量内容。

0
投票

Javascript 是松散类型的,如果存在强制将该字符串作为数字处理的操作,它将尝试将字符串转换为数字。

var a = "12345", b = a;    // "Pure" number strings
var c = "12345eee", d = c;    // "Tainted" number strings"
console.log (a, b, c, d);
console.log (typeof a, typeof b, typeof c, typeof d);
a ++;    // Increment, which forces a cast to a number
b += 1;    // Add 1 to the end, adds '1' to the end of string
c ++;    // Increment, forces cast to a number
d += 1;    // Add 1 to the end, adds '1' to the end of string
console.log (a, b, c, d);
console.log (typeof a, typeof b, typeof c, typeof d);

正如您从输出中看到的那样,当您递增(如 a 和 c 中)时,它会转换为一个数字,然后递增该数字(从而永久地将其转换为一个数字)。但是,当您在末尾添加一个数字时(如 b 和 d),它会获取该数字的字符串并将其添加到字符串中。

您可以在日志中看到 c 值的递增形式是 NaN - 这是由于字符导致尝试将 C 转换为数字时出错。

© www.soinside.com 2019 - 2024. All rights reserved.