首页 > 解决方案 > 如何将属性访问器作为函数参数传递?

问题描述

我想将属性访问器或对象文字“键”作为函数中的参数传递,这样我就可以在 for 循环中将它与点表示法一起使用。

例如:

let myArray = [
{
apples: 4,
bananas: 1,
},
{
apples: 10,
bananas: 2,
},
{
apples: 4,
bananas: 3,
},
]

Array.prototype.count = function(objProperty, testValue) {
  var count = 0;
  for (var i = 0; i < this.length; ++i) {
    if (this[i].objProperty === testValue) {
      count++;
    }
  }
  return count
}

console.log(myArray.count('apples', 4)) // expect: 2
console.log(myArray.count('apples', 10)) // expect: 1

标签: javascript

解决方案


您可以访问对象的属性,例如Object.propertyObjects[property] (in case, property is a string datatype)

let myArray = [
{
apples: 4,
bananas: 1,
},
{
apples: 10,
bananas: 2,
},
{
apples: 4,
bananas: 3,
},
]

Array.prototype.count = function(arrayProperty, testValue) {
  var count = 0;
  for (var i = 0; i < this.length; ++i) {
    if (this[i][arrayProperty] === testValue) {
      count++;
    }
  }
  return count
}

console.log(myArray.count('apples', 4)) // expect: 2
console.log(myArray.count('apples', 10)) // expect: 1


推荐阅读