2016-11-07 3 views
0

このコードで何が問題になっていますか? 私はなぜこの行 "arrKeys = Object.keys(source);"配列が返されているとは限りません。javascriptを使用して配列にObject.keys(obj)の戻り配列を格納しようとしましたが、 "ReferenceError:配列が定義されていません"というエラーが発生しました

function whatIsInAName(collection, source) { 
var arr = [];     // should return the array of properties and values found in the array object 
var arrkeys = []; 
arrKeys = Object.keys(source); // should return ["last"] 
var test = false; 
// Loops through the collections array object and searches for the object that matches the second argument passed to the method 
for(var i = 0; i < collection.length; i++){  
for(var j = 0; j < arrKeys.length; j++){ 
    if(collection[i].hasOwnProperty(arrKeys[j])){ 
     if(collection[i][arrKeys[j]] === source[arrKeys[j]]){ 
     test = true; 
     }else{ 
      break; 
     } 
    } else{ 
     break; 
    } 
    if(j === (arrkeys.length - 1) && test === true){ 
     arr.push(collection[i]); 
     } 
    }// end of inner for loop 
    }// end of inner for loop 
return arr; 
} 

whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }); 

答えて

0

あなたは持っているいくつかのタイプミス

var arrKeys = []; 
// ^

if(j === (arrKeys.length - 1) && test === true){ 
//   ^

function whatIsInAName(collection, source) { 
 
    var arr = [];     // should return the array of properties and values found in the array object 
 
    var arrKeys = Object.keys(source); // should return ["last"] 
 
    var test = false; 
 
    // Loops through the collections array object and searches for the object that matches the second argument passed to the method 
 
    for (var i = 0; i < collection.length; i++) { 
 
     for (var j = 0; j < arrKeys.length; j++) { 
 
      if (collection[i].hasOwnProperty(arrKeys[j])) { 
 
       if (collection[i][arrKeys[j]] === source[arrKeys[j]]) { 
 
        test = true; 
 
       } else { 
 
        break; 
 
       } 
 
      } else { 
 
       break; 
 
      } 
 
      if (j === (arrKeys.length - 1) && test === true) { 
 
       arr.push(collection[i]); 
 
      } 
 
     }// end of inner for loop 
 
    }// end of inner for loop 
 
    return arr; 
 
} 
 

 

 
console.log(whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }));

関連する問題