Javascript 中数组与对象的实例化。什么时候数组是对象,什么时候获取数组的方法?

Instantiation of Array vs. Objects in Javascript. When is an array an object and when does it get the methods of an array?

我在 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});

    };

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

如果您是因为遇到类似问题而阅读本文,那么问题是 newSections.length() 应该是 newSections.length。我恨我自己。不过,在我弄明白之前,出于某种原因,我认为状态 currentSections 中的数组实际上并不是一个数组。这让我想到了我的问题,什么时候数组是 Javascript 中的数组?我是不是理解错了 'typeof' returns?

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

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

Difference between Objects & Arrays

Despite just being objects under the hood, arrays behave very differently from regular objects. The reason is the Array.prototype object, which has all the Array specific methods. Every new array inherits these extra methods from Array.prototype.

Key thing to note is that the value of the prototype property of Array.prototype is Object.prototype. This means two things:

  1. Arrays are just objects but with some extra methods.
  2. There is nothing an object can do that an array can’t.

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