简体   繁体   English

检查一个值是否与另一个值相等

[英]Check if a value is equal with another

I have some code that should loop through an array of objects and if the name value is repeated anywhere in array, the code should display "repeatedName".我有一些代码应该遍历一个对象数组,如果name值在数组中的任何地方重复,代码应该显示“repeatedName”。 If not "not repeatedName".如果不是“不重复的名字”。

 export default function App() { const arr = [ { name: "John", age: 22 }, { name: "Julia", age: 28 }, { name: "John", age: 22 }, { name: "Bill", age: 22 } ]; return ( <div className="App"> {arr.map((i, k) => ( <p> {arr[k + 1].== undefined && i.name === arr[k + 1]?name: "repeatedName"; "not repeatedName"} </p> ))} </div> ); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Now i get this:现在我明白了:

 not repeatedName not repeatedName not repeatedName not repeatedName

But the expected result is:但预期的结果是:

 not repeatedName not repeatedName repeatedName not repeatedName
demo: https://codesandbox.io/s/unruffled-shaw-0mdxi?file=/src/App.js:450-462 How to change my code to get the described result? 演示: https://codesandbox.io/s/unruffled-shaw-0mdxi?file=/src/App.js:450-462如何更改我的代码以获得描述的结果?

In order to get the duplicates, you will need to store the unique names in another array, then reference that array within the loop of the object.为了获得重复项,您需要将唯一名称存储在另一个数组中,然后在 object 的循环中引用该数组。

The following will loop through the object and add the name of the person to the array.下面将循环遍历 object 并将此人的姓名添加到数组中。 Then when it continues through the loop, the name is checked with names we already know about.然后,当它继续循环时,将使用我们已经知道的名称检查名称。

 const uniqueNames = [] const people = [ { name: "John", age: 22 }, { name: "Julia", age: 28 }, { name: "John", age: 22 }, { name: "Bill", age: 22 } ] people.forEach((person) => { if (uniqueNames.indexOf(person.name) > -1) { console.log('Repeated') return } uniqueNames.push(person.name) console.log('Not repeated') })

Here's another take on the task (just for the heck of it): (Carl's solution is a more elegant one)这是另一个任务(只是为了它):(Carl 的解决方案更优雅)

  const arr = [
    {
      name: "John",
      age: 22
    },
    {
      name: "Julia",
      age: 28
    },
    {
      name: "John",
      age: 22
    },
    {
      name: "Bill",
      age: 22
    }
  ];


  return (
    <div className="App">

      {arr.map((i,k)=>{

          const isFound = k-1 > 0 && arr.slice(0, k-1).some( el => {
            return el.name === i.name; 
          })
          return isFound ? <p>repeatedName</p> : <p>not repeatedName</p>
      })}

    </div>
  );
}

Assuming you want to check if the name previously appeared anywhere in the array, you can do this with map - but it's going to look fairly clumsy and inelegant:假设您想检查该名称以前是否出现在数组中的任何位置,您可以使用map来执行此操作 - 但它看起来相当笨拙和不优雅:

{arr.map((i, k) => (
    <p>
      {arr[k - 1] !== undefined && arr.slice(0, k).some(obj => obj.name === arr[k].name) 
        ? "repeatedName"
        : "not repeatedName"}
    </p>
))}

Although I am in general a fan of the "functional style" using map and so on, here I think it's more appropriate to use a more imperative style with a loop and some internal state:虽然我通常是使用map等的“函数式风格”的粉丝,但在这里我认为使用带有循环和一些内部 state 的命令式风格更合适:

const getRepeatedStates = arr => {
    const names = [];
    const result = [];
    for (let i = 0; i < arr.length; i++) {
        const currentName = arr[i].name;
        result.push(names.includes(currentName) ? "repeatedName" : "not repeatedName";
        names.push(currentName);
    } 
    return result;
}

And then in your returned JSX, use然后在你返回的 JSX 中,使用

{getRepeatedStates(arr).map(text => (<p>{text}</p>)} 

There is a handy JavaScript object that makes it very easy to identify duplicates like these.有一个方便的 JavaScript object 可以很容易地识别像这样的重复项。

It's called Set .它叫做Set Use Set.prototype.add() to add to the set, and Set.prototype.has() to determine if a value is in the set.使用Set.prototype.add()添加到集合中,使用Set.prototype.has()确定值是否在集合中。 A value can exist only once in a Set.一个值在 Set 中只能存在一次。

 const arr = [ { name: "John", age: 22 }, { name: "Julia", age: 28 }, { name: "John", age: 22 }, { name: "Bill", age: 22 } ]; const nameSet = new Set(); let nameStats = arr.map(el => { let status = nameSet.has(el.name)? "repeatedName": "not repeatedName"; nameSet.add(el.name); return status; }); console.log('nameStats:', nameStats);

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

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