检查项目是否在对象中

时间:2021-04-26 02:17:19

标签: javascript object

我目前正在做一个名为 Two Sum https://leetcode.com/problems/two-sum/ 的问题,我想检查一个项目是否在一个集合中。我写了以下代码:

function twoSum(arr, target) {
  const hash = {};
  const res = [];

  for(let i = 0; i<arr.length; i++) {
    const num = arr[i]; 
    const diff = target - num; 

    if(diff in hash) {
      res.push(hash[diff], i);
      return res;
    }
    hash[num] = i;
  }

  return [];
  
}

twoSum([3,3], 6) // [0,1]

特别是这里检查:

if(diff in hash) 

我想知道是否可以将其更改为:

if(hash[diff])

我认为这是有道理的,因为我相信这个检查会返回 true,因为这里的相反将检查差异是否已经在集合中:

if(!hash[diff])

那为什么没有像我预期的那样工作?

1 个答案:

答案 0 :(得分:0)

import React from 'react'; import { FlatList, StyleSheet, Text, View } from 'react-native'; const styles = StyleSheet.create({ container: { flex: 1, paddingTop: 22 }, item: { padding: 10, fontSize: 18, height: 44, }, img: { width: 100, height: 100 }, }); const FlatListBasics = () => { return ( <View style={styles.container}> <FlatList data={[ {key: 'Devin', image: 'image1.png'}, {key: 'Dan', image:'image2.png'}, ]} renderItem={({item}) => <Image source={item.image} style={styles.img} /><Text style={styles.item}>{item.key}</Text>} /> </View> ); } export default FlatListBasics; 检查 diff in hash 是否是对象的属性

diff 检查 diff[hash] 处的 value 是否为真。

因为您的 diff 从 0 开始,这就是您赋予对象的值:

i
for(let i = 0; i<arr.length; i++) {

hash[num] = i; 在第一次迭代时将是 false,因此它不会通过测试。

你可以让它工作

i

如果你愿意。

相关问题