Home > Web Front-end > JS Tutorial > in_array function implemented in JavaScript_javascript skills

in_array function implemented in JavaScript_javascript skills

WBOY
Release: 2016-05-16 16:38:37
Original
1329 people have browsed it

In JS, there is no function that can be used directly to determine whether a value is in an array. For example, there is the in_array() function in PHP. But we can write a function like in_array() to determine whether a value is in the function.

/**
 * JS判断一个值是否存在数组中
 */
 
// 定义一个判断函数
var in_array = function(arr){
  // 判断参数是不是数组
  var isArr = arr && console.log(
      typeof arr==='object' ? arr.constructor===Array ? arr.length ? arr.length===1 ? arr[0]:arr.join(','):'an empty array': arr.constructor: typeof arr 
    );
 
  // 不是数组则抛出异常
  if(!isArr){
    throw "arguments is not Array"; 
  }
 
  // 遍历是否在数组中
  for(var i=0,k=arr.length;i<k;i++){
    if(this==arr[i]){
      return true;  
    }
  }
 
  // 如果不在数组中就会返回false
  return false;
}
 
// 给字符串添加原型
String.prototype.in_array = in_array;
// 给数字类型添加原型
Number.prototype.in_array = in_array;
 
// 声明一个数组
var arr = Array('blue','red','110','120');
 
// 字符串测试
var str = 'red';
var isInArray = str.in_array(arr);
alert(isInArray); // true
 
// 数字测试
var num = 119;
var isInArray = num.in_array(arr);
alert(isInArray); // false
Copy after login

If the input is not an array, an exception will be thrown

/**
 * JS判断一个值是否存在数组中
 */
 
// 定义一个判断函数
var in_array = function(arr){
  // 判断参数是不是数组
  var isArr = arr && console.log(
      typeof arr==='object' &#63; arr.constructor===Array &#63; arr.length &#63; arr.length===1 &#63; arr[0]:arr.join(','):'an empty array': arr.constructor: typeof arr 
    );
 
  // 不是数组则抛出异常
  if(!isArr){
    throw "arguments is not Array"; 
  }
 
  // 遍历是否在数组中
  for(var i=0,k=arr.length;i<k;i++){
    if(this==arr[i]){
      return true;  
    }
  }
 
  // 如果不在数组中就会返回false
  return false;
}
 
// 给字符串添加原型
String.prototype.in_array = in_array;
// 给数字类型添加原型
Number.prototype.in_array = in_array;
 
// 声明一个数组
var arr = null;
 
// 字符串测试
var str = 'red';
var isInArray = str.in_array(arr);
alert(isInArray); // uncaught exception: arguments is not Array
Copy after login

Report an error directly:

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template