Javascript Funky array mishap

后端 未结 5 1889
慢半拍i
慢半拍i 2020-12-06 00:09
function a() {
  var b = [\"b\"];
  console.log(b);
  //console.log(b.slice());
  b = b.push(\"bb\"); 
}
a();

In a \"perfect\" world you would thin

5条回答
  •  感情败类
    2020-12-06 00:28

    Confirmation (if needed) of Guffa's answer :

    function a() {
      var b = ["b"];
      console.log (b); 
      console.log (' ' + b); 
      console.log (b); 
      console.log (b.toString ()); 
      console.log (b);
      b = b.push("bb"); 
      console.log (b);
    }
    a();
    

    Chrome outputs :

    ["b", "bb"]
     b
    ["b", "bb"]
    b
    ["b", "bb"]
    2
    

    Note how every log referencing the object shows the "anomolous" result and each one which requires the evaluation of an expression does not. Note also the final log which shows that b is set to the value value 2, since the value returned by push is the new length of the array.

    So, to avoid this issue ensure that each log parameter involves the evaluation of an expression.

提交回复
热议问题