73

I realise there is a lot of topics on this subject but I believe this one is different:

The goal is to get an value from an array on a random location then delete this value.

I use this part by John Resig (the creator of jQuery) to remove an element but it doesn't seem to listen to the location I give it

Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};

this is how I use it

var elements = ['#1','#2','#3','#4']
var R1 = Math.floor(Math.random() * elements.length),
E1 = elements.slice(R1,1)
elements.remove(R1)
var R2 = Math.floor(Math.random() * elements.length),
E2 = elements.slice(R2,1)
elements.remove(R2)
var R3 = Math.floor(Math.random() * elements.length),
E3 = elements.slice(R3,1)
elements.remove(R3)
var R4 = Math.floor(Math.random() * elements.length),
E4 = elements.slice(R4,1)

The problem is the remove function, it doesn't work when removing a object on a specific location I believe.

4
  • 1
    You didn't write this did you? This is exactly the same implementation that John Resig (the creator of jQuery) wrote. Commented Jun 15, 2013 at 16:17
  • it is, i found the first part here sorry for not mentioning it, I'm new here Commented Jun 15, 2013 at 16:18
  • What should your code do? Commented Jun 15, 2013 at 16:45
  • It should give a random id out of 4 to 4 functions but never one double, so basically i'm tring to get different combination of 1 to 4 Commented Jun 15, 2013 at 16:56

1 Answer 1

24

You are using elements.slice(R3,1) wrong. Second argument means not the length of the array you want to get, but the zero-based index of the element when slice method should stop. So your code is saying "Give me elements from index R3 till index 1", and the only one time when it will work: elements.slice(0, 1). If you just need to get one element - use elements[R1]. If you need to get array with one element you can keep using slice with elements.slice(R1, R1 + 1);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.