0

Is there a way to give a specific index, in an array, a value. In PHP, I could just do this $arr[index] = val;

Right now, I use

Array.prototype.insert = function (index, item) {
  this.splice(index, 0, item);
};

And

var mute = [];
mute.insert(index, 'value');

But, if the array is empty, the index will still be 0. How do I get the right index?

4
  • In the event of an empty array what do you want the function to do? Presumably you can test the array length (this.length) and do something different in that event. Without telling us what you want to happen it's difficult to provide specific, or useful, advice without lots of guessing. How do you define "the right index"? Commented Jun 7, 2016 at 20:00
  • " the index will still be 0" - exactly, because an array indexes start with 0 Commented Jun 7, 2016 at 20:02
  • var arr = []; arr[10]="sparse";. Here you have a sparse array of arr.length == 11; // true with only one defined item at index position 10 and the rest is undefined. Commented Jun 7, 2016 at 20:02
  • Why don't you just use object[index] = some_value;? You can always use Object.keys(object) to iterate over the indexes. Arrays should be continuous (or whatever name it's called), not sparse, and that's what you have all the array methods for. Or you can implement your own version of Array, keeping track of all the indexes inside it, with desired functionality. Commented Jun 7, 2016 at 20:07

1 Answer 1

5

Try the following var mute = []; mute[index] = 'value';

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

2 Comments

if we do mute[10] = 'value' on the empty array, its length will become 11. Is it the thing the OP wants?
Correct. There's no other option to achieve 'give a specific index' otherwise we are discussing an Object such as Java's Map interface. The following would do that trick var mute = {}; mute[index] = 'value';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.