我先从代码开始:var s = [\'hi\'];console.log(s);s[0] = \'bye\';console.log(s);很简单,对吧?响应此代码,Firefox 控制台显示:[ \'hi\' ][ “...
我将从代码开始:
var s = ["hi"];
console.log(s);
s[0] = "bye";
console.log(s);
很简单,对吧?Firefox 控制台响应此消息并显示:
[ "hi" ]
[ "bye" ]
太棒了,但是 Chrome 的 JavaScript 控制台(7.0.517.41 beta)显示:
[ "bye" ]
[ "bye" ]
是我做错了什么吗,还是 Chrome 的 JavaScript 控制台在评估我的数组时特别懒惰?
根据Eric的解释,这是由于 console.log()
排队,并且打印了数组(或对象)的后续值。
可能有 5 种解决方案:
1. arr.toString() // not well for [1,[2,3]] as it shows 1,2,3
2. arr.join() // same as above
3. arr.slice(0) // a new array is created, but if arr is [1, 2, arr2, 3]
// and arr2 changes, then later value might be shown
4. arr.concat() // a new array is created, but same issue as slice(0)
5. JSON.stringify(arr) // works well as it takes a snapshot of the whole array
// or object, and the format shows the exact structure