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

后端 未结 2 947
醉酒成梦
醉酒成梦 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:27

    Let us see the first line return function(data, propertyName) here data is the array of objects to be filtered against propertyName(category in this case).

    Then we define var keys = {} i.e, an empty object.

    Now through for loop we are putting the value of propertyName(category in this case) into variable val.

    So for example the first object of data array is like this [{ product: "product 1", category: 'Category 3'}, ....]

    Thus the value of val = data[i][propertyName] translates to data[0][category], which evaluates to Category 3.

    Now the line angular.isUndefined(keys['Category 3']) would evaluate to true for if condition (here we are asking if the given condition is undefined, which evaluates to true, thus if condition passes).

    Within if loop we set the keys[val] = true, so that again this category name is not pushed to the results array.

    0 讨论(0)
  • 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 {<val>: true, <other key>: ...,}

    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

    0 讨论(0)
提交回复
热议问题