我无法将参数传递给javascript array.prototype.findIndex(callback [,thisArg])API。 javascript文档指定可以传递参数但我没有运气。 这是API参考Array.prototype.findIndex()
我在API中看到了这种语法:
arr.findIndex(callback[, thisArg])
这是我当前的实现,但我不喜欢它使用全局创建的变量实现的方式,它不是简单的测试代码。
var vm = this; //angular context
//List of objects
vm.someList = [{storeId: "1", name:"Carmel", quantity:"25", orderNumber:"12345"},
{storeId: "2", name:"Chocolate", quantity:"25", orderNumber:"23456"},
{storeId: "3", name:"Vanilla", quantity:"25", orderNumber:"34567"},
{storeId: "4", name:"Cinnamon", quantity:"25", orderNumber:"45678"}];
//List of items marked with priority
vm.priorityList = [{storeId: "3", name:"Vanilla", quantity:"25", orderNumber:"34567", priority: "true"}];
//For loop finds index of criteria to perform operation on someList[i] element
for(var i =0; i < vm.priorityList.length; i++){
//itemToFind created in global scope.
vm.itemToFind = vm.priorityList[i];
var index = vm.someList.findIndex(findPriorityIndex);
//Don't worry about the operation being performed.
console.log(index);
}
//callback fn used
function findPriorityIndex(element, index, array){
return (element.storeId === vm.itemToFind.storeId
&& element.orderNumber ===vm.itemToFind.orderNumber);
}
我尝试使用以下语法将该参数传递给回调中的thisArg,但都导致尝试失败。我也承认API提到参数将在回调中被引用,并且我在回调函数中进行了这样的调整。
vm.someList.findIndex(findPriorityIndex[, vm.priorityList[i]]);
vm.someList.findIndex(findPriorityIndex(vm.priorityList[i]));
vm.someList.findIndex([findPriorityIndex, vm.priorityList[i]]);
如果有人能提供关于如何将参数传递给回调函数的任何信息,我将非常感激。
答案 0 :(得分:6)
基本上你在回调中设置了thisArg
的findIndex,this
。
for (var i = 0; i < vm.priorityList.length; i++) {
index = vm.someList.findIndex(findPriorityIndex, vm.priorityList[i]);´
// set thisArg ^^^^^^^^^^^^^^^^^^
console.log(index);
}
// callback fn used
function findPriorityIndex(element, index, array) {
return element.storeId === this.storeId && element.orderNumber === this.orderNumber;
// access this here ^^^^ and ^^^^
}
答案 1 :(得分:0)
简单地说,使用 this 来访问参数,如下所述
const fruits = [{id:1,label:"apple"},{id:2,label: "banana"}, {id:3,label:"cantaloupe"}
];
function checkIndex(element) {
return element.label == this;
}
console.log(fruits.findIndex(checkIndex,'banana'));