如何检查二维数组是否包含字符串?
How to check if a two dimensional array includes a string?
我有一个二维数组arr[cols][rows]
。
我想知道 cols 是否包含字符串 "hello"。
我如何使用 .includes("hello")
方法进行检查。
请注意,我正在尝试在一个循环中使用计数器 i
来检查它。所以我必须做类似 arr[i][0].includes("hello");
的事情
您可以将 array.prototype.some
与 array.prototype.includes
一起使用。应该是:
var datas= [
["aaa", "bbb"],
["ddd", "eee"]
];
function exists(arr, search) {
return arr.some(row => row.includes(search));
}
console.log(exists(datas, 'ddd'));
console.log(exists(datas, 'xxx'));
我有一个二维数组arr[cols][rows]
。
我想知道 cols 是否包含字符串 "hello"。
我如何使用 .includes("hello")
方法进行检查。
请注意,我正在尝试在一个循环中使用计数器 i
来检查它。所以我必须做类似 arr[i][0].includes("hello");
您可以将 array.prototype.some
与 array.prototype.includes
一起使用。应该是:
var datas= [
["aaa", "bbb"],
["ddd", "eee"]
];
function exists(arr, search) {
return arr.some(row => row.includes(search));
}
console.log(exists(datas, 'ddd'));
console.log(exists(datas, 'xxx'));