在包含两个的Javascript数组中选择另一个元素

Pick the other element in a Javascript array containing two

本文关键字:选择 另一个 元素 数组 Javascript 包含两      更新时间:2024-03-09

我有一个javascript数组,如:

var arr = ['black', 'white'];

现在,如果我有一个包含其中一个元素的变量,我如何轻松地获得另一个?例如

var color = 'black';
var otherColor = '???'; // should be 'white', how can I get it?

我正在寻找最简单/最干净的方法。

另外,我不想改变原来的数组。

感谢

答案

关于:

var otherColor = arr[1 - arr.indexOf(color)]

您可以使用Array.prototype.filter:

var arr = ['black', 'white'];
var color = 'black';
var otherColor = arr.filter(function(item){ return item !== color })[0];

三元if语句:

var otherColor = arr[0] === color ? arr[1] : arr[0];

arr.filter(x => x !== color)[0]

这里有一个ES6解决方案,它使用析构函数将其放入混合中。

const arr = ['black', 'white']; // our list of values.
const [black, white] = arr; // destructured into variables black and white
const color = 'black'; 
cont otherColor === black ? black : white;
var otherColor = arr[1 - arr.indexOf(color)]