PHP 里面有个很好用的函数叫“in_array”,它可以用来检查数组中是否存在某个值,现在可以通过 prototype 向 javascript 数组添加一个类似的方法,简单但是实用。
<script type="text/javascript">
Array.prototype.inArray = function (value)
// Returns true if the passed value is found in the
// array. Returns false if it is not.
{
var i;
for (i=0; i < this.length; i++)
{
// Matches identical (===), not just similar (==).
if (this[i] === value){
return true;
}
}
return false;
};
var arr = ['苹果', '香蕉', '梨', '桔子', '西瓜'];
alert(arr.inArray('桔子'));// true
alert(arr.inArray('核桃'));// false
</script>
Array.prototype.inArray = function (value)
// Returns true if the passed value is found in the
// array. Returns false if it is not.
{
var i;
for (i=0; i < this.length; i++)
{
// Matches identical (===), not just similar (==).
if (this[i] === value){
return true;
}
}
return false;
};
var arr = ['苹果', '香蕉', '梨', '桔子', '西瓜'];
alert(arr.inArray('桔子'));// true
alert(arr.inArray('核桃'));// false
</script>
本文介绍了一种向JavaScript数组添加类似PHP中in_array方法的技术,通过简单的代码实现即可轻松检查数组内是否存在指定值。
3446

被折叠的 条评论
为什么被折叠?



