2015-02-24 49 views
-1

值我正在寫檢查,如果一個n維數組具有一定值的函數:檢查隨機多維數組中存在的Javascript

function checkVal(array, value){ 
    if (value exists) { 
     return true; 
    } else { 
     return false; 
    } 
} 

我的問題是,我想這個函數來工作任何隨機數組,無論其維數或元素類型如何。我試圖首先弄平這個陣列,但是隻設法做了幾個維度。

編輯: 可能陣列的一些實例:

var arr1 = ['1','3',['a','b'],'4,5'];

var arr2 = ['a','b',['c','d',['e',['e',['e',['e',['e',['e',['e',['e',['e',['e',['f',['f',['f',['f',['f',['f',['g',['g',['g',['g',['g',['g',['g',['h']]]]]]]]]]]]]]]]]]]]]]]]]];

+3

請添加一些數組的例子... – Vishwanath 2015-02-24 10:31:21

+0

@Vishwanath新增了! – Clarity 2015-02-24 10:37:38

回答

2

沒有必要扁平化陣列,這只是額外的工作。你需要的是一個遞歸函數:

function checkVal(array, value) { 
    // `Array#some` loops through the array until the iterator 
    // function returns true; it returns true if the iterator 
    // does at some point, false otherwise 
    return array.some(function(entry) { 
     // If this entry in the array is an array, recurse 
     if (Array.isArray(entry)) { 
      return checkVal(entry, value); 
     } 

     // It isn't, do an equality check 
     return entry === value; 
    }); 
} 

Array#someArray.isArray都是ES5功能,所以目前在任何現代的瀏覽器,都可以勻/ polyfilled年紀稍長的像IE8。或者,當然,上述可以用無聊的for循環和舊的Object.prototype.toString.call(entry) === "[object Array]"測試來重寫是否是數組。

請注意,我已經使用===進行相等性檢查。如果你需要更復雜的東西,比如對象等價而不是身份等等,那麼在那裏做出改變。

例/基本測試:

function checkVal(array, value) { 
 
    // `Array#some` loops through the array until the iterator 
 
    // function returns true; it returns true if the iterator 
 
    // does at some point, false otherwise 
 
    return array.some(function(entry) { 
 
    // If this entry in the array is an array, recurse 
 
    if (Array.isArray(entry)) { 
 
     return checkVal(entry, value); 
 
    } 
 

 
    // It isn't, do an equality check 
 
    return entry === value; 
 
    }); 
 
} 
 

 
snippet.log(checkVal(['a', 'b', 'c'], 'b'));   // true 
 
snippet.log(checkVal(['a', 'b', 'c'], 'd'));   // false 
 

 
snippet.log(checkVal([['a'], ['b', 'c']], 'c'));  // true 
 
snippet.log(checkVal([['a'], ['b', 'c']], 'd'));  // false 
 

 
snippet.log(checkVal([['a'], [['b', ['c']]]], 'c')); // true 
 
snippet.log(checkVal([['a'], [['b', ['c']]]], 'd')); // false
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

+0

這正是我期待的!非常感謝! – Clarity 2015-02-24 10:43:37

0

你需要一個遞歸函數在陣列的所有子檢查

function searchValue(arr, val){ 
    // found another array 
    if(arr instanceof Array){ 
    for(var i=0; i<arr.length; i++){ 
     if(searchValue(arr[i],val)){ 
     return true; // stop on first valid result 
     } 
    } 
    return false; 
    }else{ 
    // found a leaf 
    return arr == val; // <-- if you want strict check, use === 
    } 
} 

if(searchValue(myArray, 'my variable')){ 
    // do something.. 
} 

它可以在任何瀏覽器中