使用 indexOf 进行多源控制
Multiple source control with indexOf
这是我的第一个数组:
kaos = [1,2,6,9,15,18,21];
这是第二个数组:
zeus = [1,3];
我想在 indexOf(1, 3)
的 kaos 中搜索 zeus
这是有效的:
kaos.indexOf(1)!=-1;
但这不起作用:
kaos.indexOf(1, 3)!=-1;
或
这也行不通:
kaos.indexOf(1, 3, 9)!=-1;
我想搜索indexOf(1,3,7, vs),我该怎么办
您可以使用 Array#map
并遍历所需的项目以检查 kaos
是否包含 zeus
的元素。结果是一个布尔值数组,反映状态。
var kaos = [1, 2, 6, 9, 15, 18, 21],
zeus = [1, 3],
result = zeus.map(function (value) {
return kaos.indexOf(value) !== -1;
});
console.log(result);
现实世界的例子。
(我建议使用数组而不是字符串来保存数据。)
它使用Array#filter
in combination with Array#every
,其中returns true
仅当所有检查元素returns true
.
var $scope = { names: [{ prop_Name: 'Location 1', amenities: '1, 3, 5, 8, 11' }, { prop_Name: 'Location 2', amenities: '1, 3, 5, 8, 11' }, { prop_Name: 'Location 3', amenities: '1, 4, 14, 7, 11' }, { prop_Name: 'Location 4', amenities: '17, 3, 25, 8, 11' }, { prop_Name: 'Location 5', amenities: '2, 34, 50, 8, 11' }] },
amenities = [3, 8],
result = $scope.names.filter(function (n) {
return amenities.every(function (a) {
return n.amenities.split(', ').map(Number).indexOf(a) !== -1;
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
它还确保您找到独一无二的。
var kaos = [1, 2, 6, 9, 15, 18, 21],
zeus = [1, 15];
zeus.every(function (element) {
if (kaos.indexOf(element) > -1) {
kaos.splice(kaos.indexOf(element), 1);
return true;
};
这是我的第一个数组:
kaos = [1,2,6,9,15,18,21];
这是第二个数组:
zeus = [1,3];
我想在 indexOf(1, 3)
这是有效的:
kaos.indexOf(1)!=-1;
但这不起作用:
kaos.indexOf(1, 3)!=-1;
或
这也行不通:
kaos.indexOf(1, 3, 9)!=-1;
我想搜索indexOf(1,3,7, vs),我该怎么办
您可以使用 Array#map
并遍历所需的项目以检查 kaos
是否包含 zeus
的元素。结果是一个布尔值数组,反映状态。
var kaos = [1, 2, 6, 9, 15, 18, 21],
zeus = [1, 3],
result = zeus.map(function (value) {
return kaos.indexOf(value) !== -1;
});
console.log(result);
现实世界的例子。
(我建议使用数组而不是字符串来保存数据。)
它使用Array#filter
in combination with Array#every
,其中returns true
仅当所有检查元素returns true
.
var $scope = { names: [{ prop_Name: 'Location 1', amenities: '1, 3, 5, 8, 11' }, { prop_Name: 'Location 2', amenities: '1, 3, 5, 8, 11' }, { prop_Name: 'Location 3', amenities: '1, 4, 14, 7, 11' }, { prop_Name: 'Location 4', amenities: '17, 3, 25, 8, 11' }, { prop_Name: 'Location 5', amenities: '2, 34, 50, 8, 11' }] },
amenities = [3, 8],
result = $scope.names.filter(function (n) {
return amenities.every(function (a) {
return n.amenities.split(', ').map(Number).indexOf(a) !== -1;
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
它还确保您找到独一无二的。
var kaos = [1, 2, 6, 9, 15, 18, 21],
zeus = [1, 15];
zeus.every(function (element) {
if (kaos.indexOf(element) > -1) {
kaos.splice(kaos.indexOf(element), 1);
return true;
};