Pro AngularJS - Could you help explain part of this code?

后端 未结 2 972
醉酒成梦
醉酒成梦 2021-01-15 12:03

I am reading a book called Pro AngularJS by Apress and I am just trying to ensure I understand all of the code and I am a bit baffled by the following code.

Below is

2条回答
  •  醉话见心
    2021-01-15 12:46

    Put simply, it's just a way to remember that we already have processed the value val, and do not which to return duplicates, if it comes along again in the loop.

    You have to put something in the keys object, like keys[val] = true;, so that keys[val] becomes defined in the next loop iteration.

    If you don't put anything into keys[val], angular.isUndefined(keys[val]) in the next loop with same value val will evaluate to true, and then your result would be duplicated (which isn't unique)

    Explanation and answer to your questions

    if the keys[val] is undefined (what does this mean)?

    Basically means the key val doesn't exist in the object keys, e.g. an object {'age': 45} contains the key age but doesn't contain the key weight

    Then keys[val] is set to true (what does this do?)

    This sets the key val of the object keys to true, so somewhere keys object looks like this {: true, : ...,}

    So after that step, the key val is defined for the object keys, therefore angular.isUndefined(keys[val]) condition is false

    what is the purpose of keys[val] in the first place? Sorry, just not clear on what it is doing.

    The code uses an object keys = {} which behaves like a key/value data structure (a dictionary, or a map, in other languages), the goal is to remember that we already have processed val

    If you don't remember the values you have already processed (returned), then you will return duplicates, and therefore your unique filter will no longer return unique values, which is the purpose of the code here

提交回复
热议问题