我想传递一个属性acessor或object literal' 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
&#13;
答案 0 :(得分:3)
您可以访问对象的属性,例如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
&#13;