Home  >  Article  >  Web Front-end  >  Detailed explanation of how to use in_array function to determine array usage in JavaScript

Detailed explanation of how to use in_array function to determine array usage in JavaScript

伊谢尔伦
伊谢尔伦Original
2017-07-25 14:43:033053browse

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(&#39;blue&#39;,&#39;red&#39;,&#39;110&#39;,&#39;120&#39;);
 
// 字符串测试
var str = &#39;red&#39;;
var isInArray = str.in_array(arr);
alert(isInArray); // true
 
// 数字测试
var num = 119;
var isInArray = num.in_array(arr);
alert(isInArray); // false

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===&#39;object&#39; ? arr.constructor===Array ? arr.length ? arr.length===1 ? arr[0]:arr.join(&#39;,&#39;):&#39;an empty array&#39;: 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 = &#39;red&#39;;
var isInArray = str.in_array(arr);
alert(isInArray); // uncaught exception: arguments is not Array

will report an error directly.

The above is the detailed content of Detailed explanation of how to use in_array function to determine array usage in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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