jquery - 未捕获的类型错误 : append is not a function

标签 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,那么是什么原因导致的呢?

最佳答案

TypeError: people.append is not a function

意味着 append 不是 Array 方法,所以你应该使用 push 而不是将元素添加到数组中:

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

希望这有帮助。

$(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]);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于jquery - 未捕获的类型错误 : append is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41247137/

相关文章:

javascript - 变量作为 jQuery 选择器焦点

jquery - 如何循环遍历多个div

ajax - 在 src 标记中显示图像,响应文本不是 base64

Google Chrome 中的 Jquery 动画问题

javascript - AJAX 强制页面刷新(但不应该)

jquery - 使用 HTML 重新创建 iOS UITableView

javascript - 查找表是否仅包含空格

javascript - 动态创建多个div并分配id

javascript - 在javascript中遍历DOM

javascript - Angularjs:如何将特定数据传递给模态