问题
I have an array that looks like this.
var array[["a","b"],["c","d"],["e","f"]];
I want to be able to search through the array for the string "d"
and return the corresponding value "c"
.
回答1:
try:
function find_str(array){
for(var i in array){
if(array[i][1] == 'd'){
return array[i][0];
}
}
}
EDIT:
function find_str(array){
for(var i=0;i<array.length;i++){
if(array[i][1] == 'd'){
return array[i][0];
}
}
}
回答2:
A general function for getting all the elements of the arrays that contain the specified value. The following function uses several methods of Array.prototype
: filter
, indexOf
, map
, slice
, splice
and concat
for flattening the arrays.
var array = [["a","b"],["c","d"],["c","e","f"]];
function findBy(arr, val) {
var ret = arr.filter(function(el) {
return el.indexOf(val) > -1;
}).map(function(el) {
var res = el.slice();
res.splice(el.indexOf(val), 1);
return res;
});
return Array.prototype.concat.apply([], ret);
}
findBy(array, 'c');
// -> ["d", "e", "f"]
findBy(array, 'b');
// -> ["a"]
findBy(array, 'g');
// -> []
来源:https://stackoverflow.com/questions/30228691/how-can-i-find-a-string-in-a-two-dimensional-array