以下は回答者の憶測が含まれています. 有力な根拠については不明です.
↓
根拠を追加
以下は間違った解釈です.
console.log
メソッドに直接オブジェクトを指定した場合の動作に原因があるように見受けられます.
console.log
メソッドの動作を
console.log
メソッドが実行されると, WEBブラウザはログキューにその内容を保管する.
- スクリプトの実行が完了(もしくはタイマーによる出力?)するとログの内容をコンソールに出力する.
であると仮定すると, 1でconsole.log
の引数としてオブジェクトへの参照を渡した際に, 2の過程で初めてオブジェクトが直列化されることになります. 従って, sort
メソッド実行前にも関わらず, array[1]
の内容がソート済みとなっているように見えるのです.
https://developer.mozilla.org/en-US/docs/Web/API/Console/log
によれば
A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a reference to the object, which is not necessarily the 'value' of the object at the moment in time you call console.log(), but it is the value of the object at the moment you click it open.
要約
console.log
で記録されるものはその時点でのオブジェクトに対する参照値であり, その時点でのオブジェクトの内部値ではない. なので, コンソールからログ内のオブジェクトにアクセスすると, その時点での値が表示される.
この問題はJSON.stringify
メソッドを適用する, もしくはtoString
メソッドを実装しておく(Array
オブジェクトについて正しく動作している要因)等, ログの内容を文字列として固定することで回避できます.
JavaScript
1 (function(){
2 'use strict';
3 var array = {
4 1:['c','a','d','b'],
5 2:['aa','cc','bb'],
6 }
7 console.log(array[1]);//["c", "a", "d", "b"]①
8 console.log(JSON.stringify(array));//②
9 array[1].sort();
10 console.log(array[1]);//["a", "b", "c", "d"]③
11 console.log(JSON.stringify(array));//④
12 })();
Text
1//コンソールでの出力結果
2Array [ "c", "a", "d", "b" ]
3{"1":["c","a","d","b"],"2":["aa","cc","bb"]}
4Array [ "a", "b", "c", "d" ]
5{"1":["a","b","c","d"],"2":["aa","cc","bb"]}
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/01/27 14:34
2018/01/27 14:45