If you are not sure if the item is in the list you should do:
var idx = my_list.indexOf(old_item) if (idx !== -1) { my_list[idx] = new_item }
But I think this is the best way to do this.
Setting the value at index -1 will not result in an error, but will still modify the object in the same way as setting the key in a universal js object:
var my_list = [1, 2, 3]; var old_item = 5; var new_item = 10; my_list[my_list.indexOf(old_item)] = new_item; // my_list is [1, 2, 3, '-1': 10] // my_list.length is still 3 // Object.keys(my_list) is [ '0', '1', '2', '-1' ]
So you probably don't want to do this.
source share