在 Javascript 中实例化数组与对象.数组何时是对象,何时获取数组的方法?



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

此代码生成错误: 未捕获的类型错误:newSection.length 不是一个函数

如果你因为遇到类似的问题而阅读这篇文章,问题是newSection.length()应该是newSection.length。我恨自己。在我想通这一点之前,出于某种原因,我认为我在状态 currentSections 中的数组实际上不是一个数组。这让我想到了我的问题,数组在 Javascript 中什么时候是数组?我是否误解了什么是"类型"回报?

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.prototype对象,它具有所有Array特定方法。每个新阵列 从Array.prototype继承这些额外的方法。

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

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

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

最新更新