JavaScript中定义自定义数组的3种方法

JavaScript 数组是用于存储项目集合的通用数据结构。

有多种方法可以使用 JavaScript 中的原型来定义自定义数组方法。以下是三种常见的方法:


1、直接赋值:
您可以直接将函数分配给Array.prototype。该方法直接修改Array对象的原型:

// 定义名为 "customMethod "的自定义方法
Array.prototype.customMethod = function() {
   
// Your custom logic here
    console.log(
"Custom method called");
};

//现在,您可以在任何数组上使用自定义方法
const myArray = [1, 2, 3];
myArray.customMethod();
// Output: Custom method called


2、Object.defineProperty:
您可以使用 Object.defineProperty 在 Array.prototype 上定义带有 getter 函数的属性:

// 定义名为 "customMethod "的自定义方法
Object.defineProperty(Array.prototype, 'customMethod', {
    value: function() {
       
// Your custom logic here
        console.log(
"Custom method called");
    },
    enumerable: false,
// 如果希望方法可枚举,则设置为 true
    configurable: true
//如果希望以后删除该方法,则设置为 true
});

// 现在,您可以在任何数组上使用自定义方法
const myArray = [1, 2, 3];
myArray.customMethod();
// Output: Custom method called


此方法提供了对属性属性的更多控制。

3、Object.create:
您可以使用自定义方法创建一个新对象,然后将该对象的原型设置为 Array.prototype:

// 定义名为 "customMethod "的自定义方法
const customArrayMethods = {
    customMethod: function() {
       
// Your custom logic here
        console.log(
"Custom method called");
    }
};

// 将 customArrayMethods 的原型设置为 Array.prototype
Object.setPrototypeOf(Array.prototype, customArrayMethods);

// 现在,您可以在任何数组上使用自定义方法
const myArray = [1, 2, 3];
myArray.customMethod();
// Output: Custom method called

4、使用 for、for…of 或 forEach 等直接迭代数组遭遇问题
当您想要迭代数组的元素时,通常使用 for、for…of 或 forEach 等循环。然而,在迭代通过其原型添加了其他属性的数组时,存在细微差别。

在我们深入研究解决方案之前,让我们了解为什么数组可能在其迭代中包含原型属性。

在 JavaScript 中,您可以向数组原型添加属性或方法。

Array.prototype.myProperty = function() {
    console.log(“Hello”);
}

将函数myPreoperty分配给Array.prototype。这是直接修改Array对象的原型prototype

现在,使用数组Array了:如果您有一个包含元素 10、15 和 20 的数组 myArr,并且您对其进行迭代:

Array.prototype.myProperty = function() {
    console.log("Hello");
}

const myArr = [10, 15, 20]

for (let ele in myArr) {
    console.log(myArr[ele]);
}


输出:

10
15
20
[Function (anonymous)]

您会注意到它会打印附加的 myProperty 以及数组元素:

让我们过滤原始属性:
要只打印数组的原始属性(不包括prototype属性),需要使用 hasOwnProperty 方法进行检查。下面是具体方法:

Array.prototype.myProperty = function() {
    console.log("Hello");
}

const myArr = [10, 15, 20]

for (let ele in myArr) {
    if (myArr.hasOwnProperty(ele)) {
        console.log(myArr[ele]);
    }
}

10
15
20

这段代码确保只打印数组中的原始元素,而忽略任何原型属性。