Javascript更新函数内的全局对象

时间:2017-08-22 13:02:23

标签: javascript

我看到我的全局变量是一个对象,正在函数内进行修改。

以下是我创建的示例:



var globalVarForTest = ["dfbsdfbsdfb", "sfgb", "gtsgt", "ttt"];

function testingError() {

  console.log("BEFORE")
  console.log(globalVarForTest);
  for (var i = 0; i < globalVarForTest.length; i++) {
    console.log(globalVarForTest[i]);
  }


  //Modifying Local Variable
  var localVarforTest = globalVarForTest;
  for (var i = 0; i < localVarforTest.length; i++) {
    localVarforTest[i] = localVarforTest[i].length;
  }




  console.log("AFTER")
  console.log(globalVarForTest);
  for (var i = 0; i < globalVarForTest.length; i++) {
    console.log(globalVarForTest[i]);
  }

}

testingError();
&#13;
&#13;
&#13;

该函数打印全局变量的BEFORE和AFTER不同值。

如何在函数内设置局部变量等于全局数组,以便在函数中不修改全局数组?

2 个答案:

答案 0 :(得分:1)

您必须clone it without reference

var globalVarForTest = ["dfbsdfbsdfb","sfgb","gtsgt","ttt"];

var temp = globalVarForTest.slice(0);

console.log(temp);
temp.push('temp');
console.log(temp);
console.log(globalVarForTest);

答案 1 :(得分:0)

您可以使用JSON本机解析方法从和转换为obj ..

&#13;
&#13;
var globalVarForTest = ["dfbsdfbsdfb","sfgb","gtsgt","ttt"];

            function testingError(){

            console.log("BEFORE")
            console.log( globalVarForTest );
            for( var i=0; i<globalVarForTest.length; i++ ){
                    console.log( globalVarForTest[i]);
            }


              //Modifying Local Variable
            var localVarforTest = JSON.parse(JSON.stringify( globalVarForTest ));
            console.log( localVarforTest );
            for( var i=0; i< localVarforTest.length; i++ ){
                    console.log( localVarforTest[i]);
            }


            console.log("AFTER");
            console.log( globalVarForTest );
            for( var i=0; i<globalVarForTest.length; i++ ){
                    console.log( globalVarForTest[i]);
            }


            }

testingError();
&#13;
&#13;
&#13;