未捕获类型错误:追加不是函数

时间:2016-12-20 16:38:01

标签: jquery

我想创建一个由人组成的阵列。并将它们记录到控制台。

这是我的代码:

$(document).ready(function () {
    function Person(firstName) {
        this.firstName = firstName;
        console.log('Person instantiated');
    }
    var people = new Array;
    people.append(new Person("Alice1"));
    people.append(new Person("Alice2"));
    people.append(new Person("Alice3"));
    people.append(new Person("Alice4"));

    for (var i = 0; i < people.length; i++) {
        console.log(people[i]);
    }
});

然而,控制台正在吐出这个:

main.js:4 Person instantiated
jquery-3.1.1.min.js:2 jQuery.Deferred exception: people.append is not a function TypeError: people.append is not a function
    at HTMLDocument.<anonymous> (http://localhost:8383/p5/js/main.js:7:8)
    at j (http://localhost:8383/p5/js/jquery-3.1.1.min.js:2:29948)
    at k (http://localhost:8383/p5/js/jquery-3.1.1.min.js:2:30262) undefined
r.Deferred.exceptionHook @ jquery-3.1.1.min.js:2
k @ jquery-3.1.1.min.js:2
jquery-3.1.1.min.js:2 Uncaught TypeError: people.append is not a function
    at HTMLDocument.<anonymous> (main.js:7)
    at j (jquery-3.1.1.min.js:2)
    at k (jquery-3.1.1.min.js:2)
(anonymous) @ main.js:7
j @ jquery-3.1.1.min.js:2
k @ jquery-3.1.1.min.js:2

我正在我的主js文件之前初始化HTML文件中的jquery.min.js,那是什么导致了这个?

1 个答案:

答案 0 :(得分:2)

  

TypeError:people.append不是函数

表示append不是 Array 方法,因此您应该使用 push 来添加元素到一个数组:

people.push(new Person("Alice1"));

希望这有帮助。

&#13;
&#13;
$(document).ready(function () {
  function Person(firstName) {
    this.firstName = firstName;
    console.log('Person instantiated');
  }
  var people = new Array;
  people.push(new Person("Alice1"));
  people.push(new Person("Alice2"));
  people.push(new Person("Alice3"));
  people.push(new Person("Alice4"));

  for (var i = 0; i < people.length; i++) {
    console.log(people[i]);
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;