简体   繁体   English

检查数组输入 - Javascript

[英]Checking input against array - Javascript

I'm totally new, so excuse any faux pas. 我是全新的,所以请原谅任何失礼。 I searched for a solution, but couldn't find anything that answered my question, or at least anything that I could understand. 我搜索了一个解决方案,但找不到任何能回答我问题的内容,或者至少找不到任何我能理解的内容。

So here goes: I'd like to iterate through each object in this array and check if firstName ("Akira", in this case) matches up to any of the firstNames within my "contacts" array. 所以这里是:我想迭代这个数组中的每个对象,并检查firstName(在这种情况下是“Akira”)是否与我的“contacts”数组中的任何firstNames匹配。 At this stage, I'd just like to return the index number of the object(if this is possible). 在这个阶段,我只想返回对象的索引号(如果可能的话)。 If not, please let me know how I can do this, in the most elementary, 5-year old way possible. 如果没有,请让我知道如何以最基本的,5年的方式做到这一点。 Thank you! 谢谢!

var contacts = [
{
    "firstName": "Akira",
    "lastName": "Laine",
    "number": "0543236543",
    "likes": ["Pizza", "Coding", "Brownie Points"]
},
{
    "firstName": "Harry",
    "lastName": "Potter",
    "number": "0994372684",
    "likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
    "firstName": "Sherlock",
    "lastName": "Holmes",
    "number": "0487345643",
    "likes": ["Intriguing Cases", "Violin"]
},
{
    "firstName": "Kristian",
    "lastName": "Vos",
    "number": "unknown",
    "likes": ["Javascript", "Gaming", "Foxes"]
}

function lookUpProfile(firstName, prop){
  for (var i = 0; i < contacts.length; i++) {
   if (contacts[i][firstName] == firstName){
      return i; 
   } 
  }   
}

lookUpProfile("Akira", "likes");

your code has an error you have no closing "]" for your contacts variable, also when accessing object properties use code contacts[i]["firstname"] 您的代码有一个错误,您没有为您的联系人变量关闭“]”,也是在访问对象属性时使用代码contacts[i]["firstname"]

 var contacts = [ { "firstName": "Akira", "lastName": "Laine", "number": "0543236543", "likes": ["Pizza", "Coding", "Brownie Points"] }, { "firstName": "Harry", "lastName": "Potter", "number": "0994372684", "likes": ["Hogwarts", "Magic", "Hagrid"] }, { "firstName": "Sherlock", "lastName": "Holmes", "number": "0487345643", "likes": ["Intriguing Cases", "Violin"] }, { "firstName": "Kristian", "lastName": "Vos", "number": "unknown", "likes": ["Javascript", "Gaming", "Foxes"] }]; function lookUpProfile(firstName, prop){ var ret = -1; for (var i = 0; i < contacts.length; i++) { if (contacts[i]["firstName"] == firstName){ ret = i; } } console.log(ret); } lookUpProfile("Akira", "likes"); 

you can refer this answer. 你可以参考这个答案。 following are the best way to access JSON objects. 以下是访问JSON对象的最佳方法。

 function lookUpProfile(firstName, prop){
      for (var i = 0; i < contacts.length; i++) {
       if (contacts[i]["firstName"] == firstName){
          return i; 
       } 
      }   
    }

or 要么

function lookUpProfile(firstName, prop){
  for (var i = 0; i < contacts.length; i++) {
   if (contacts[i].firstName == firstName){
      return i; 
   } 
  }   
}

Object properties can be accessed by dot notation, or your have to quotes your key as it is a string. 可以通过点表示法访问对象属性,或者您必须引用键,因为它是一个字符串。

 if (contacts[i].firstName == firstName){
  return i; 
 } 

check fiddle 检查小提琴

You forgot to close up contacts array and called property wrong inside the function 您忘记关闭联系人数组并在函数内部调用属性错误

 var contacts = [ { "firstName": "Akira", "lastName": "Laine", "number": "0543236543", "likes": ["Pizza", "Coding", "Brownie Points"] }, { "firstName": "Harry", "lastName": "Potter", "number": "0994372684", "likes": ["Hogwarts", "Magic", "Hagrid"] }, { "firstName": "Sherlock", "lastName": "Holmes", "number": "0487345643", "likes": ["Intriguing Cases", "Violin"] }, { "firstName": "Kristian", "lastName": "Vos", "number": "unknown", "likes": ["Javascript", "Gaming", "Foxes"] } ]; function lookUpProfile(firstName, prop){ for (var i = 0; i < contacts.length; i++) { if (contacts[i].firstName === firstName){ console.log(i); return i; } } } lookUpProfile("Sherlock", "likes"); 

Your code is confusing the variable firstName to the key firstName. 您的代码将变量firstName与键firstName混淆。

In your lookUpProfile function, change this line : 在lookUpProfile函数中,更改以下行:

if(contacts[i].firstName == firstName)

Explanation 说明

Just change your function like - 只需改变你的功能 -

function lookUpProfile(firstName, prop){
 for (var i = 0; i < contacts.length; i++) {
  if (contacts[i].firstName === firstName){
  return i; 
   } 
  }   
}

And Dont use '==' Use '===' in javaScript 并且不要在javaScript中使用'=='使用'==='

Your code has some minor errors, but except those, everything looks fine to me. 你的代码有一些小错误,但除了那些,一切看起来都不错。 The first error is that you haven't closed the contacts array. 第一个错误是您没有关闭contacts数组。 You have opened the array here: var contacts = [ and started listing the contacts, but after that, you have to close this array with this character ] . 您已在此处打开了数组: var contacts = [并开始列出联系人,但之后,您必须使用此字符关闭此数组]

And the second issue is something that you are really care about. 第二个问题是你真正关心的问题。 When you are checking the firstName you are passing the same parameter that you give to the function, that being said, you are not checking if contacts[i].firstName === "Akira" but contacts[i].Akira === "Akira" . 当您检查firstName时,您传递的是与该函数相同的参数,也就是说,您不会检查contacts[i].firstName === "Akira"但是contacts[i].Akira === "Akira" And none of the objects has Akira property. 并且没有一个对象具有Akira属性。

You can try contacts[i].firstName or contacts[i].["firstName"] . 您可以尝试contacts[i].firstNamecontacts[i].["firstName"] Both will solve your problem. 两者都将解决您的问题。

You can find more explanation here: http://www.w3schools.com/js/js_properties.asp 您可以在此处找到更多解释: http//www.w3schools.com/js/js_properties.asp

Looking at the arguments you want to accept in the function, I assume that you want the property of the given contact. 查看您希望在函数中接受的参数,我假设您需要给定联系人的属性。

You can access a property of an object using dot notation like contacts[0].firstName . 您可以使用点符号(如contacts[0].firstName访问对象的属性。

You can also access it using array with associated key like contacts[0]["firstName"] . 您也可以使用带有关联键的数组来访问它,例如contacts[0]["firstName"]

 var contacts = [ { "firstName": "Akira", "lastName": "Laine", "number": "0543236543", "likes": ["Pizza", "Coding", "Brownie Points"] }, { "firstName": "Harry", "lastName": "Potter", "number": "0994372684", "likes": ["Hogwarts", "Magic", "Hagrid"] }, { "firstName": "Sherlock", "lastName": "Holmes", "number": "0487345643", "likes": ["Intriguing Cases", "Violin"] }, { "firstName": "Kristian", "lastName": "Vos", "number": "unknown", "likes": ["Javascript", "Gaming", "Foxes"] } ]; function lookUpProfile(firstName, prop){ for (var i = 0; i < contacts.length; i++) { if (contacts[i].firstName == firstName){ console.log(i); return contacts[i][prop]; } } } console.log(lookUpProfile("Akira", "likes")); 

Ok so starting with your search function: 好的,从搜索功能开始:

// Prop parameter wasn't used so I removed it.
function lookUpProfile(firstName){
  for (var i = 0; i < contacts.length; i++) {
   // If you are using an array accessor for the properties you want to throw
   // quotes around it.  You could also access it like so contacts[i].firstName.
   // What you had previously was using the value of "firstName" to try to
   // access the "firstName" property.  What your code actually tried was to
   // access the "Akira" property which doesn't exist.  
   // 
   // Also until you get stronger in javascript it is safer to use the "===" 
   // strict equality as this checks for type and value equality.  (ex 0 === "0" will be false)
   if (contacts[i]['firstName'] === firstName){
      // By returning here you are saying that no other object can have the
      // same "firstName" value.  If that isn't true you will want to store
      // the index in a variable outside of this loop and return it later.
      //
      // Another option here is to just return "contacts[i]" that way you
      // have a reference to the object you are searching for.
      return i; 
   } 
  }   
}

In general when starting out I would suggest using strict equality ("==="/"!==") as it will behave more intuitively and fail sooner. 一般来说,当我开始时,我会建议使用严格相等(“===”/“!==”),因为它会表现得更直观,更快失败。 If you use "=="/"!=" javascript will try to convert types for you if they don't match which can lead to unintended behavior. 如果您使用“==”/“!=”,javascript将尝试为您转换类型,如果它们不匹配可能导致意外行为。

If you write this code then you will get the output like this [0, undefined, undefined, undefined]. 如果你编写这段代码,那么你将得到像这样的输出[0,undefined,undefined,undefined]。 Where 0 is your matched character index. 其中0是匹配的字符索引。

var lookUpProfile = function(matchString) { var returnVal = function(item,index) { if(item.firstName == matchString) return index; }; return returnVal; }; var profileIndexHolder = contacts.map(lookUpProfile('Sherlock')) console.log(profileIndexHolder);

var lookUpProfile = function(matchString) { var returnVal = function(item,index) { if(item.firstName == matchString) return index; }; return returnVal; }; var profileIndexHolder = contacts.map(lookUpProfile('Sherlock')) console.log(profileIndexHolder);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM