Reputation: 4318
Seen this question a lot, but cannot find something that's what i'm looking for.
onClick
I push an item to an array I have, however, if there's 3 items in my array I don't want to be able to push items anymore.
var selectedData = [];
I set my empty variable.
var index = selectedData.indexOf(3);
I then get the index of my array which is 3
if (index > 3) {
selectedData.splice(index, 1);
}
Then within my if statement
I say, if my index which is 3, is bigger then 3, then splice at index
and remove one.
selectedData.push(TheThing);
I then push TheThing
to my array if the if statement above isn't true.
However, I have a variable var arrayLength = selectedData.length;
that grabs the length, and when I console log it, it starts at 0
and splices items anything after 4. Not 3.
Any idea what i've done wrong or misunderstood? Thanks
More full example of my code
var selectedData = [];
myElement.on('click', function() {
var index = selectedData.indexOf(3);
if (index > 3) {
selectedData.splice(index, 1);
}
var arrayLength = selectedData.length;
console.log(arrayLength, 'the length');
});
So in short, onClick
check my array and remove anything after the third that gets added into my array.
Upvotes: 1
Views: 91
Reputation: 1591
This could work.
myElement.on('click', function() {
if(selectedData.length > 3){
selectedData = selectedData.splice(0, 3);
}
console.log(selectedData.length, 'the length');
});
Upvotes: 0
Reputation: 5264
you can use this scenario
var selectedData = [];
myElement.on('click', function() {
//if selectedData length is less than 3, push items
});
Upvotes: 0
Reputation: 866
var index = selectedData.indexOf(3); simply give you the index of the element of the array that has value 3 Example
selectedData = [ 0, 3 , 2];
alert( selectedData.indexOf( 3 ) ); // this will alert "1" that is the index of the element with value "3"
Upvotes: 0
Reputation: 1354
you can override push()
method of your array like this:
var a = [];
a.push = function(){}
or like this
a.push = function (newEl){
if(this.length <3){
Array.prototype.push.call(this, newEl)
}
}
This is not complete example because push() can take many arguments and you should to handle this case too
Upvotes: 0
Reputation: 21421
Do you want this to behave as a stack or a queue?
So your code here:
var index = selectedData.indexOf(3);
Is not grabbing the 3rd index - its grabbing the first index where it sees 3, or -1 if it doesn't. Replace your if statement with,
if (selectedData.length > 3) {
selectedData.pop() // removes last element (stack)
// or
selectedData = selectedData.slice(1) //remove first element (queue)
}
Upvotes: 1
Reputation: 43870
I think you need to try var arrayLength = selectedData.length -1;
You start at 0 like a normal array, but don't you start with an empty array?
Plus when you use .length
, it returns the true count of the array or collection not a 0 index.
`
Upvotes: 0