Array JavaScript Mengandungi - Trik CSS

Anonim

Objek javascript sangat bagus, tetapi kadang-kadang mereka kehilangan beberapa fungsi / kaedah kecil yang berguna. Contoh di atas adalah dengan Arrays. Sangat senang mengetahui sama ada item tersebut terdapat dalam barisan anda atau tidak. Anda boleh menulis fungsi yang menggunakan array dan item yang anda periksa, tetapi lebih baik untuk menambahkan kaedah mengandung (item) ke objek Array.

Memperluas Susunan 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; )

Penggunaan

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