JavaScript整数到字符串输出不匹配期望值

时间:2018-10-08 23:42:38

标签: javascript

在对JS用法进行一些基本测试期间,我一直在研究对象的生成/数组的添加。到目前为止,我已经使用两种不同的方法来解决此问题:

  • 具有变化的字段然后添加的单个全局对象。
  • 一种工厂函数,该函数会生成相同的对象,并进行额外的操作以显示细微的差异(值字段加1)

尽管在运行时没有错误,但全局对象属性上的value字段始终输出2(此处的值假定随循环而增加),而函数方法似乎没有问题。您知道为什么会这样吗?

我生成的最终输出是"[{"name":"Hello","value":2},{"name":"Hello World","value":1},{"name":"Hello","value":2},{"name":"Hello World","value":2},{"name":"Hello","value":2},{"name":"Hello World","value":3}]"(来自console.log(JSON.stringify(testArray));)。

我期望输出"[{"name":"Hello","value":0},{"name":"Hello World","value":1},{"name":"Hello","value":1},{"name":"Hello World","value":2},{"name":"Hello","value":2},{"name":"Hello World","value":3}]"

相关功能和对象的代码可以在下面找到。

定义全局变量:

var globalVariable =
{
    name: undefined,
    value: undefined
}

工厂功能:

function globalVariableGen(name, valueInput)
{
    return output =
    {
        name: name,
        value: valueInput + 1
    }
}

数组生成函数:

function test2()
{
    var i, testArray = [];
    for (i = 0; i < 3; i++)
    {
        alert(i.toString());
        globalVariable.name = "Hello";
        globalVariable.value = i;
        testArray.push(globalVariable);

        testArray.push(globalVariableGen("Hello World", i));
    }
    console.log(JSON.stringify(testArray));
}

亲切的问候, 阴影

1 个答案:

答案 0 :(得分:4)

这是因为javascript是传递引​​用,并且您指的是多次添加到数组中的同一globalVariable。然后,该数组包含多个指向globalVariable的指针,它们完全相同。

如果将console.log(JSON.stringify(testArray)添加到循环中,您将看到此行为。

> "[{"name":"Hello","value":0},{"name":"Hello World","value":1}]"

> "[{"name":"Hello","value":1},{"name":"Hello World","value":1},{"name":"Hello","value":1},{"name":"Hello World","value":2}]"

> "[{"name":"Hello","value":2},{"name":"Hello World","value":1},{"name":"Hello","value":2},{"name":"Hello World","value":2},{"name":"Hello","value":2},{"name":"Hello World","value":3}]"