javascript - 如何将属性访问器作为函数参数传递?
问题描述
我想将属性访问器或对象文字“键”作为函数中的参数传递,这样我就可以在 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
解决方案
您可以访问对象的属性,例如Object.property
或Objects[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
推荐阅读
- angular - 如何在 Angular 中转换时间数据
- flutter - 我如何实现这种类型的底片颤动
- javascript - 如何在反应中处理异步状态更新
- bash - 从 git diff 获取状态
- python-3.x - Python 环境或安装未安装 spyder-kernels 模块或其正确版本
- in-app-purchase - 如何实施应用内联属网络营销计划?
- javascript - 纯Javascript:如何检查1)数组A是否有数组B的任何元素和2)如果数组A有任何元素数组B没有
- java - 如何尽可能快地运行 maven 项目的测试?
- postgresql - Grafana 图表按天或月分组?
- python - 如何使用 Selenium 更改浏览器(Chrome)的语言?