简体   繁体   中英

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).

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?

The filter method returns a new array, it doesn't modify the original. So in your case, you still have access to cmp.items.items , which is the original array. So you can simply do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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