简要说明:如果var c = familyArray.includes("Bart");
返回false
,但是如果var c = familyArray.includes("Homer");
返回true
我也希望在Bart
的情况下也是如此,因为它也包含在数组中。
下面是我的数组:
var familyArray = ["Marge", "Homer", ["Bart", "Lisa", "Maggie"]];
var a = familyArray.indexOf("Bart");
var b = familyArray[2][0];
var c = familyArray.includes("Bart");
document.getElementById("demo").innerHTML = c;
console.log(a);
console.log(b);
<p id="demo"></p>
答案 0 :(得分:5)
您的问题是您有一个多维数组,数组includes
将不会搜索内部数组。因此,您需要先对数组进行展平,然后再进行搜索。在这里,如果您的数组的维数不止2个,我将Infinity
用作参数:
var familyArray = ["Marge", "Homer", ["Bart", "Lisa", "Maggie"]];
var c = familyArray.flat(Infinity).includes("Bart");
console.log(c); // true;
的另一种方法
答案 1 :(得分:2)
您正在使用嵌套数组,可以先使用.flat
:
familyArray.flat().includes('Bart')
答案 2 :(得分:0)
您正在内部数组中搜索。你可以这样。
var familyArray = ["Marge", "Homer", ["Bart", "Lisa", "Maggie"]];
console.log(familyArray[2].includes("Bart"));
答案 3 :(得分:0)
您可以这样做:
var c = familyArray.flat(1).includes("Bart");
答案 4 :(得分:0)
为此尝试flat
方法
var familyArray = ["Marge", "Homer", ["Bart", "Lisa", "Maggie"]];
var familyArrayFlatten = familyArray.flat();
var a = familyArrayFlatten.indexOf("Bart");
var b = familyArrayFlatten[2][0];
var c = familyArrayFlatten.includes("Bart");
console.log(a);
console.log(b);
console.log(c);