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?
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"?0var arr = []; arr[10]="sparse";. Here you have a sparse array ofarr.length == 11; // truewith only one defined item at index position 10 and the rest isundefined.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 ofArray, keeping track of all the indexes inside it, with desired functionality.