我想将属性访问器或对象文字“key”作为函数中的参数传递,以便我可以在 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](如果属性是字符串数据类型)
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
关于javascript - 如何将属性访问器作为函数参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50891030/