如果值包含,如何获取数组中键的索引?

How do you get the index of a key in a array by and if value contains?

这就是我的意思。

var brands = [['brand: LV'], ['brand: Apple']]...

有了这个,我想定位(索引)say..Apple。手动,我可以轻松做到

brands[1]

但这是动态更新的,因此索引将是随机的。

使用findIndex() or indexOf().

示例:brands.findIndex(doc => doc[0] === 'brand: Apple').

你的格式有点不方便,通常你会有一个对象数组而不是像这样的字符串数组,但无论如何你仍然可以:

let brands = [ ['brand: LV'],['brand: Apple']]
let f = brands.findIndex(subarray => subarray.some(i => i.includes('Apple')))
console.log(f, brands[f])

请注意,由于您拥有这些数组,因此它考虑了其中之一具有多个值的可能性。所以考虑:

let  brands = [['brand: LV'], ['brand: Sony', 'brand: Apple']]
let f = brands.findIndex(subarray => subarray.some(i => i.includes('Apple')))
console.log(f, brands[f])
如果你知道每个子数组只有一个值,你可以测试一下:

let brands = [ ['brand: LV'],['brand: Apple']]
let f = brands.findIndex(subarray => subarray[0].includes('Apple'))
console.log(f, brands[f])

由于您的数据是数组的数组,简单的 includesindexOf 不会在顶层工作,您需要测试每个元素。使用 findIndex 允许您依次将自定义函数应用于每个元素:

let brands = [
  ['brand: LV'],
  ['brand: Apple']
];

function findBrand(name) {
    let testValue = `brand: ${name}`;
    return brands.findIndex( elem => elem.includes(testValue) );
}

console.log(findBrand('Apple'))