如何像内置函数一样在变量上应用用户定义的函数



我正试图通过使用点(.(运算符而不是作为参数发送来创建一个用户定义的函数来处理变量。所以在我的程序中,我有一个整数数组,我需要对每个数组执行,而不是使用forEach内置函数。我知道这听起来很垃圾。因此,我创建了一个名为somefunc的函数,并有一个称为arr.的变量

我做过的代码

var somefunc = function()
{
console.log('this function executed');
}
var arr=[1,2];
arr.somefunc();

我试图模仿的代码

var friends = ["Mike", "Stacy", "Andy", "Rick"];
friends.forEach(function (eachName, index){
console.log(index + 1 + ". " + eachName); // 1. Mike, 2. Stacy, 3. Andy, 4. Rick
});

我想为Each执行这样的函数。

尝试将函数添加到数组proptotype中以创建所需的行为。使用此访问当前数组。

Array.prototype.customIterator = function() {
// this.forEach(() => {})
}

您应该在这里使用原型。将somefunc添加到内置在Array类型中的JS的原型中。

Array.prototype.somefunc = function() {
this.forEach(function (eachName, index) {
console.log(index + 1 + ". " + eachName);
});
// or you can use other ways to itarate over all array elemets
// like a simple for loop for (let i=0; i < this.length; i++) {...}
// 'this' here refers to an array you are running somefunc on
}
var friends = ["Mike", "Stacy", "Andy", "Rick"];
friends.somefunc();

forEachmap等每个函数也存在于Arrayprototype中,它们是prototype的属性。您可以通过执行console.log(Array.prototype);来查看它。您可以看到Arrayprototype有许多现成的内置方法,您可以使用句点调用这些方法。因此,您只需通过为Array.prototype分配一个新的函数属性来添加自己的函数,如上面的片段所示。

最新更新