将字符串保存到变量和console.log时,拆分字符串会得到不同的结果

Splitting a string gives different result when saved to variable and when console.log-ing it

本文关键字:字符串 结果 拆分 变量 保存 console log      更新时间:2023-09-26

我有一个非常简单的函数,它在$location发生变化时执行(见下文)。问题是,当$location.path() == "/browser"时,分配中出现的$location.path().split("/")返回["browser"],但直接在console.log内部运行会返回["", "browser"]。如何合理地解释这种差异?

angular.module("blah", [])
.controller("navigation", function($scope, $location) {
    var updatePage = function() {
        var temp = $location.path().split("/");
        console.log($location.path(), $location.path().split("/"), temp);
        $scope.page = temp.splice(0,1)[0];
        $scope.args = temp;
        //console.log($scope.page);
    };
    $scope.changePage = function(path) {
        if (path.match("^https?:")) {
            window.location = path;
        } else {
            $location.path(path);
        }
    };
    $scope.args = [];
    $scope.$on("$locationChangeSuccess", function(event, data) {
        updatePage();
    });
    updatePage();
});

您可能会看到类似以下代码的"问题":

var temp = $location.path().split("/");
$scope.page = temp.splice(0,1)[0];
...
console.log($location.path(), $location.path().split("/"), temp);

在记录时,temp已经splice dsplice(与slice不同)也从原始阵列中移除了elment。


更新:

另一个可能的原因是:
Firefox(与Chrome不同)在记录时不会记录对象的,而是对对象的
引用(数组也是对象)。因此,阵列的任何后续修改(例如拼接)也会影响记录的对象/阵列。

如果您改为记录JSON.stringify(temp),您应该会看到预期的结果。