类型错误:控制台.log(...) 不是函数

2022-08-30 04:03:53

我真的很困惑如何获得控制台.log不是1091行上的函数。如果我删除下面的闭包,则第 1091 行不会抱怨此类错误。Chrome 版本 43.0.2357.130(64 位)。

enter image description here

代码如下:

$scope.columnNameChanged = function (tableColumn) {
    setDirtyColumn(tableColumn);
    //propagate changes to the key fields
    for (var i = 0; i < $scope.tableIndexes.length; ++i) {
        for (var j = 0; j < $scope.tableIndexes[i].columnName.length; ++j) {
            if ($scope.tableIndexes[i].columnName[j] === tableColumn.previousName) {
                console.log('xxx', $scope.tableIndexes[i].columnName[j])
                (function (i, j) {
                    $timeout(function () {
                        console.log($scope.tableIndexes[i].columnName[j])
                        $scope.tableIndexes[i].columnName[j] = tableColumn.name.toUpperCase();
                        console.log($scope.tableIndexes[i].columnName[j])
                    });
                })(i, j);
            }
        }
    }
};

答案 1

溶液

只需在 .... 之后加上一个分号 ();console.log()


解释

该错误很容易重现,如下所示:

console.log()
(function(){})

它试图作为参数传递给返回值,其本身不是函数,而是实际上(检查)。这是因为 JavaScript 将其解释为 .但是.log控制台一个功能。function(){}console.log()undefinedtypeof console.log();console.log()(function(){})

如果您没有对象,您会看到console

引用错误:未定义控制台

如果你有对象,但没有你会看到的方法consolelog

类型错误:控制台.log不是函数

然而,你所拥有的是

类型错误:控制台.log(...) 不是函数

请注意函数名称后面的 。对于这些,它指的是函数的返回值。(...)

换行符不会将这两个表达式作为单独的语句分开,因为 JavaScript 的自动分号插入 (ASI) 规则


尊重;

如果没有分号,所有这些代码片段都会导致各种意外错误:

console.log() // As covered before
() // TypeError: console.log(...) is not a function
console.log() // Accessing property 0 of property 1 of the return value…
[1][0] // TypeError: console.log(...) is undefined
console.log() // Like undefined-3
-3 // NaN
let a, b;
const array = Array.from({ length: 2 })

// Now, let’s use destructuring:
[a, b] = array; // ReferenceError: can't access lexical declaration 'array' before initialization
let a, b;
const array = Array.from({ length: 2 }).fill(1),
  array2 = Array.from({ length: 2 })

// Now, let’s use destructuring. Attempt to get the two 1’s from `array` as `a` and `b`:
[a, b] = array;
console.log(a, b); // undefined undefined

另一个例子

您可以看到经常使用链接方法或链接属性访问器的情况:(...)

string.match(/someRegEx/)[0]

如果未找到该正则表达式,则该方法将返回,并且 on 上的属性访问器将导致 — 返回值为 。在返回值为 的情况下。nullnullTypeError: string.match(...) is nullnullconsole.log(...)undefined


答案 2

该错误表示 的返回值不是函数。您缺少一个分号:console.log()

console.log('xxx', $scope.tableIndexes[i].columnName[j]);
//                                                      ^

这使得 IIFE 的以下内容被解释为函数调用。(...)


比较 的错误消息

> var foo = {bar: undefined};
> foo.bar();
Uncaught TypeError: foo.bar is not a function

> var foo = {bar: function(){}};
> foo.bar()();
Uncaught TypeError: foo.bar(...) is not a function