简体   繁体   English

如何检查 javascript 中先前的数组长度?

[英]How to check previous array length in javascript?

I'm having this issue where I need to check if previous array length is the same as the new array length .我遇到了这个问题,我需要检查以前的数组长度是否与新的数组长度相同。


I'm working on a survey that renders questions dynamically.我正在进行一项动态呈现问题的调查。
For example let's say my survey starts with 2 questions, then if I answer question 2 it may or may not show me question number 3, and if it shows me question 3 now my array has 3 elements (each question is an element in my array).例如,假设我的调查从 2 个问题开始,那么如果我回答问题 2,它可能会或可能不会显示问题编号 3,如果它显示问题 3 现在我的数组有 3 个元素(每个问题都是我数组中的一个元素)。

Does anyone know how to keep track of previous array length and compare it with the new array length.有谁知道如何跟踪以前的数组长度并将其与新的数组长度进行比较。

I've been pulling my hair on this one for a while now.我已经在这个上拉头发有一段时间了。 Thanks a lot in advance!提前非常感谢!

Here's my code:这是我的代码:

// This is how I get the questions from my survey

var availableQuestions = cmp.items.items.filter(function(group){ return !group.collapsed; });

// This is how I get the number of questions in the array
var numberOfquestions =  availableQuestions.length;

The variable availableQuestions will always show me the new number of visible questions on the survey, but how to compare it to the previous one and check if I have more questions display on the page or not?变量availableQuestions将始终向我显示调查中可见问题的新数量,但是如何将其与前一个进行比较并检查页面上是否显示了更多问题?

The filter method returns a new array, it doesn't modify the original. filter方法返回一个数组,它不会修改原始数组。 So in your case, you still have access to cmp.items.items , which is the original array.因此,在您的情况下,您仍然可以访问cmp.items.items ,这是原始数组。 So you can simply do:所以你可以简单地做:

if (availableQuestions.length === cmp.items.items.length) {
  // They're the same length, do whatever.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM