javascript 如何选择数组中除第 i 个元素之外的所有其他值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15361189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:31:32  来源:igfitidea点击:

How to select all other values in an array except the ith element?

javascriptarrays

提问by blarg

I have a function using an array value represented as

我有一个使用数组值的函数,表示为

 markers[i]

How can I select all other values in an array except this one?

如何选择数组中除此以外的所有其他值?

The purpose of this is to reset all other Google Maps images to their original state but highlight a new one by changing the image.

这样做的目的是将所有其他 Google 地图图像重置为其原始状态,但通过更改图像来突出显示新图像。

采纳答案by DhruvPathak

Use Array?.prototype?.spliceto get an array of elements excluding this one.

使用Array?.prototype?.splice得到排除这一个元素的数组。

This affects the array permanently, so if you don't want that, create a copy first.

这会永久影响阵列,因此如果您不希望那样,请先创建一个副本。

var origArray = [0,1,2,3,4,5];
var cloneArray = origArray.slice();
var i = 3;

cloneArray.splice(i,1);

console.log(cloneArray.join("---"));

回答by Yeldar Kurmangaliyev

You can use ECMAScript 5 Array.prototype.filter:

您可以使用 ECMAScript 5 Array.prototype.filter

var items = [1, 2, 3, 4, 5, 6];
var current = 2;

var itemsWithoutCurrent = items.filter(function(x) { return x !== current; });

There can be any comparison logics instead of x !== current. For example, you can compare object properties.

可以有任何比较逻辑而不是x !== current. 例如,您可以比较对象属性。

If you work with primitives, you can also create a custom function like exceptwhich will introduce this functionality:

如果您使用原语,您还可以创建一个自定义函数,例如except将引入此功能:

Array.prototype.except = function(val) {
    return this.filter(function(x) { return x !== val; });        
}; 

// Usage example:
console.log([1, 2, 3, 4, 5, 6].except(2)); // 1, 3, 4, 5, 6

回答by Mido

You can use slice()Method

您可以使用 slice()方法

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1,3);

The slice() method returns the selected elements in an array, as a new array object.

slice() 方法将数组中选定的元素作为新的数组对象返回。

回答by mineti

You can also use the second callback parameter in Filter:

您还可以在Filter 中使用第二个回调参数:

const exceptIndex = 3;
const items = ['item1', 'item2', 'item3', 'item4', 'item5'];
const filteredItems = items.filter((value, index) => exceptIndex !== index);

回答by jWang1

With ECMAScript 5

使用 ECMAScript 5

const array = ['a', 'b', 'c'];
const removeAt = 1;
const newArray = [...array].splice(removeAt, 1);