admin管理员组文章数量:1220500
I have following code:
var a = [{a: 1}, {a: 2}, {a: 3}];
a.map(function (item, index) {
console.log('call');
if (index < 1) {
a.splice(index, 1);
}
});
But call is printed only two times, and I expect to be printed three times. I know that splice
has messed up array, but is there some workaround for this behaviour?
Thank you!
I have following code:
var a = [{a: 1}, {a: 2}, {a: 3}];
a.map(function (item, index) {
console.log('call');
if (index < 1) {
a.splice(index, 1);
}
});
But call is printed only two times, and I expect to be printed three times. I know that splice
has messed up array, but is there some workaround for this behaviour?
Thank you!
Share Improve this question edited Apr 30, 2014 at 22:49 Brad 163k55 gold badges377 silver badges552 bronze badges asked Apr 30, 2014 at 22:47 user232343user232343 2,1185 gold badges22 silver badges35 bronze badges3 Answers
Reset to default 6the callback in map has a third argument which is the array it self
var a = [{a: 1}, {a: 2}, {a: 3}];
a.map(function (item, index, a2) {
console.log('call');
if (index < 1) {
a2.splice(index, 1);
}
});
This if from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
The range of elements processed by map is set before the first invocation of callback. Elements which are appended to the array after the call to map begins will not be visited by callback. If existing elements of the array are changed, or deleted, their value as passed to callback will be the value at the time map visits them; elements that are deleted are not visited.
If you want to modify the array while you iterate it, then often times, it's just best to use a plain old for
loop because you can control the iteration and correct for your modifications.
If your modification is only a deletion of the current element, then a backwards for
loop is simplest because you don't have to do any corrections when removing the current element. Here's an example:
var x = [{a: 1}, {a: 2}, {a: 3}];
for (var i = x.length - 1; i >= 0; i--) {
if (x[i].a === 2) {
// remove current element
x.splice(i, 1);
}
}
If you don't mind creating a new array as the result of the iteration, you can use other methods such as .filter()
.
Make a shallow copy of the array:
a.slice().map(function (item, index) {
By the way, you should maybe use forEach
since you're not returning any value.
Or even better, have you considered using filter
instead?
var a = [{a: 1}, {a: 2}, {a: 3}].filter(function (item, index) {
console.log('call');
return index >= 1;
});
本文标签: javascriptCalling splice inside map functionStack Overflow
版权声明:本文标题:javascript - Calling splice inside map function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739345332a2159134.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论