首页 > 解决方案 > 做一些freecodecamp问题,我遇到了一个指导对象值的小问题

问题描述

该代码仅返回与第二个参数匹配的第一个参数中的内容,然后进行检查。 链接以防万一

我的主要关注点是 if 语句中的“source[srcKeys[i]]”。“srcKeys”单独返回“['last']”,但如果你在它前面添加'source',例如“source[srcKeys]”,你会得到“Capulet”。我的问题是为什么它返回“Capulet”而不是“['last']”,因为它针对 Object.keys 而不是值?

    function whatIsInAName(collection, source) {
  var srcKeys = Object.keys(source);



  return collection.filter((obj) => {

    for (var i = 0; i < srcKeys.length; i++) {
      if (obj[srcKeys[i]] !== source[srcKeys[i]]) {
        return false
      }
    }
    return true;
  });
}

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

标签: javascript

解决方案


but if you add 'source' in front of it such as "source[srcKeys]" you get "Capulet"

Did you actually try this?

It sounds like what you are saying is that the expression source[['last']] would evaluate to Capulet.

Let's try it:

const collection = [{
    first: "Romeo",
    last: "Montague"
  },
  {
    first: "Mercutio",
    last: null
  },
  {
    first: "Tybalt",
    last: "Capulet"
  }
];

const source = {
  last: "Capulet"
};

const srcKeys = Object.keys(source);

console.log(source[srcKeys]);

Well I'll be...another Javascript gem! Wonderful!

Here be dragons

Ok so it looks like JavaScript allows you to index into an array using an single element array as the index and it will just work.

The only thing I was able to find on the internet explaining this, is this blog post.

The post also goes on to show that even doing something like:

source[[[[srcKeys]]]]

Will also give the result Capulet.

How wonderful!

Moral of the story is: Javascript has a lot of quirks that are not immediately obvious. I would call them undefined, but Javascript seems pretty consistent in the quirky department. This is why many developers turn to other languages that compile down to Javascript simply to avoid these hidden gotchas.


My question is why its returning "Capulet" and not "['last']"

Well in this case, it will not should not return/evaluate to ['last'] unless you have a value in source which is a list containing just 'last'. Who knows, maybe there exists another hidden quirk of JavaScript that just might return ['last']. As far as I know, it should not be possible, but I've been wrong before...


推荐阅读