簡體   English   中英

嘗試使用javascript將Object.keys(obj)的返回數組存儲在數組中,但出現錯誤“ ReferenceError:未定義數組”

[英]Attempting to store the return array of Object.keys(obj) in an array using javascript, but getting the error “ReferenceError: array is not defined”

此代碼有什么問題? 我不明白為什么這行“ arrKeys = Object.keys(source);” 沒有按預期返回數組。

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" });

你有錯別字

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" })); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM