JavaScript chứa mảng - Thủ thuật CSS

Anonim

Các đối tượng Javascript thực sự rất đẹp, nhưng đôi khi chúng thiếu một số hàm / phương thức nhỏ hữu ích. Ví dụ trên là với Mảng. Thật tuyệt khi biết liệu một mục có được chứa trong mảng của bạn hay không. Bạn có thể viết một hàm lấy mảng và mục bạn đang kiểm tra, nhưng việc thêm phương thức chứa (item) vào đối tượng Array sẽ dễ dàng hơn nhiều.

Mở rộng Mảng JavaScript

/** * Array.prototype.(method name) allows you to define/overwrite an objects method * needle is the item you are searching for * this is a special variable that refers to "this" instance of an Array. * returns true if needle is in the array, and false otherwise */ Array.prototype.contains = function ( needle ) ( for (i in this) ( if (this(i) == needle) return true; ) return false; )

Sử dụng

// Now you can do things like: var x = Array(); if (x.contains('foo')) ( // do something special )