【问题标题】:Instantiation of Array vs. Objects in Javascript. When is an array an object and when does it get the methods of an array?Javascript 中数组与对象的实例化。数组什么时候是对象,什么时候得到数组的方法?
【发布时间】:2019-10-17 06:12:50
【问题描述】:

我在 C/C++/PIC 汇编和 VHDL 方面有一些经验,但对 javascript 完全迷失了方向。我正在 React 中构建一个单页应用程序,但这个问题更多的是为了更好地理解而不是解决问题(因为我已经找到了我的问题)。

我的问题是,在 Javascript 中,变量何时是数组,何时是对象?我如何区分? (鉴于 'typeof' 总是表示对象)。

如果它对某人有帮助,我最初的问题是,在我的状态下,我有一个对象数组,我需要长度。我试图用 Array.length() 来获取它,但它应该是 Array.length。在我弄清楚这一点之前浪费了 30 分钟,我提出了更多的问题。

这是我的构造函数:

constructor(props, context) {
        super(props, context);

        this.state = {
            activeItem: 'home',
            currentSections: [ { key: 'Home', content: 'Home', link: true } ]
        };

        this.handleItemClick = this.handleItemClick.bind(this);
        this.handleTabChange = this.handleTabChange.bind(this);
    }

就上下文而言,我正在为应用程序构建一个面包屑路径。为了确定在添加新元素之前是否需要弹出数组的最后一个元素,我需要 currentSections 数组的长度。

handleTabChange = (e, data) => {

        let newSections = [];

        newSections = this.state.currentSections;
        if (newSections.length() > 2) {
            newSections.pop();
        }

        let newSection = {
            key: data.panes[data.activeIndex].name,
            content: data.panes[data.activeIndex].menuItem,
            link: true
        };
        newSections.push(newSection);
                this.setState({currentSections: newSections});

    };

此代码产生错误: 未捕获的 TypeError:newSections.length 不是函数

如果您因为遇到类似问题而阅读本文,那么问题是 newSections.length() 应该是 newSections.length。我恨我自己。不过,在我弄清楚这一点之前,出于某种原因,我曾认为我处于 currentSections 状态的数组实际上并不是一个数组。这让我想到了一个问题,数组什么时候是 Javascript 中的数组?我是否误解了“typeof”返回的内容?

let newSections = [];
console.log(typeof newSections); //object
newSections = this.state.currentSections;
console.log(typeof newSections); //object
let newSections = [1,2,3];
console.log(typeof newSections); //object

我知道数组是一个对象,但是有没有办法判断一个变量是被视为数组还是普通对象?我找不到任何讨论这个的东西,但这可能是因为我不知道要搜索什么术语。

【问题讨论】:

  • Array.isArray(element); 返回真时,它是一个数组。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…(简短回答,TL;DR。长读,由 MDN 提出:web.mit.edu/jwalden/www/isArray.html)。注意:不要将“iterables”与“arrays”混用。在 javascript 中,许多类型可以是可迭代的(例如考虑字符串),但这并不一定意味着它们是数组,这只是意味着它们是可迭代的,并且碰巧它们可以在接受可迭代的方法中使用(例如 @ 987654328@等)。
  • variable instanceof Array === true
  • 谢谢。我将查看 Mozilla 文章。我会将其标记为已回答。感谢参考。

标签: javascript arrays reactjs javascript-objects instantiation


【解决方案1】:

对象和数组的区别

尽管只是底层的对象,但数组的行为非常 不同于普通物体。原因是Array.prototype 对象,它具有所有Array 特定方法。每个新数组 从Array.prototype 继承这些额外的方法。

要注意的关键是prototype 属性的值 Array.prototypeObject.prototype。这意味着两件事:

  1. 数组只是对象,但有一些额外的方法。
  2. 没有什么是对象可以做而数组不能做的。

阅读:https://www.frontendmayhem.com/javascript-arrays-objects/

【讨论】:

  • 谢谢@jonrsharpe 点赞
  • 谢谢。使用来自@briosheje 的 cmets,我认为这回答了我的问题。
猜你喜欢
  • 1970-01-01
  • 2023-03-05
  • 2010-11-08
  • 1970-01-01
  • 2017-09-23
  • 2012-02-12
  • 2011-08-09
  • 2010-11-18
  • 1970-01-01
相关资源
最近更新 更多