最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

lodash - Javascript: replace directly with index vs Array.splice() - Stack Overflow

programmeradmin3浏览0评论

Today, I came across a SO question to replace a matching object inside array of objects.

To do so, they are finding the index of the matching object inside array of objects using lodash.

var users = [{user: "Kamal"}, {user: "Vivek"}, {user: "Guna"}]
var idx = _.findIndex(users, {user: "Vivek"}); // returns 1

Now they used splice() to replace like this,

users.splice(idx, 1, {user: "Gowtham"})

but why not,

users[idx] = {user: "Gowtham"};

Now my question is, Is there any reason, not to do so or to use splice() ?

Because it is so simple to use array[index] = 'something';. Isn't it ?

Today, I came across a SO question to replace a matching object inside array of objects.

To do so, they are finding the index of the matching object inside array of objects using lodash.

var users = [{user: "Kamal"}, {user: "Vivek"}, {user: "Guna"}]
var idx = _.findIndex(users, {user: "Vivek"}); // returns 1

Now they used splice() to replace like this,

users.splice(idx, 1, {user: "Gowtham"})

but why not,

users[idx] = {user: "Gowtham"};

Now my question is, Is there any reason, not to do so or to use splice() ?

Because it is so simple to use array[index] = 'something';. Isn't it ?

Share Improve this question edited May 23, 2017 at 12:10 CommunityBot 11 silver badge asked Sep 12, 2015 at 20:36 Kamalakannan JKamalakannan J 2,9983 gold badges26 silver badges56 bronze badges 3
  • 2 It is true that using array[index] is faster than Array.splice(): jsperf./array-index-vs-splice. But your mileage may vary depending on the size of the array, perhaps? – Terry Commented Sep 12, 2015 at 20:46
  • 1 Unless you want to get the removed value (which isn't being done here), index assignment would make more sense and be most likely faster. – user1106925 Commented Sep 12, 2015 at 20:46
  • 1 Ah, one difference is that .splice() will act more like .push() if idx is beyond the .length of the array, whereas index assignment would extend the array's length. – user1106925 Commented Sep 12, 2015 at 20:50
Add a ment  | 

1 Answer 1

Reset to default 13

The only reasons they might do this are:

  1. they want to also get the previous value
  2. they want to 'cleverly' handle the case where idx == -1 by replacing the last element in the array, rather than putting it at -1, because splice will treat negative integers specially. (this doesn't seem like it would fit the use-case you described)

in most cases, arr[i] = "value"; will be better than arr.splice(i, 1, "value");

发布评论

评论列表(0)

  1. 暂无评论