Home >Web Front-end >JS Tutorial >Detailed explanation of JavaScript pseudo array usage

Detailed explanation of JavaScript pseudo array usage

小云云
小云云Original
2017-12-23 14:35:583205browse

This article mainly introduces the usage of JavaScript pseudo-array, and analyzes the concept, function, definition and simple usage of pseudo-array in the form of examples. Friends in need can refer to it. I hope it can help everyone.

What is a pseudo array in Javascript?

Pseudo array (array-like): You cannot call array methods directly or expect any special behavior from the length property, but you can still traverse them using real array traversal methods.

1. Typical is the argument parameter of the function,
2. Calling getElementsByTagName, document.childNodes, etc., they all return NodeList objects, which are pseudo arrays.

So how to convert a pseudo array into a standard array?

You can use Array.prototype.slice.call(fakeArray) to convert the array into a real Array object.

For example, use pseudo arrays to implement the summation problem of indefinite parameters.


##

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>伪数组</title>
</head>
<script>
  function add(){
    var sum=0;
    console.log(arguments);
    for(var i=0;i<arguments.length;i++){
      sum +=arguments[i];
    }
    return sum;
  }
 console.log(add(1,2,5,8));
</script>
<body>
</body>
</html>

Running results:

Convert pseudo array to standard array


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>伪数组</title>
</head>
<script>
  function add(){
    var sum=0;
    console.log(arguments instanceof Array);//可以判断下此时是不是真正数组,返回值为false;
    console.log(arguments);//此时打印的是传入的参数1,2,5,8
    var arguments=Array.prototype.slice.call(arguments);//将伪数组转化为标准数组
    arguments.push(10);//此时就可以调用标准数组的方法
    console.log(arguments instanceof Array);//可以判断下此时是不是真正数组,返回值为true;
    console.log(arguments);//此时打印的是传入的参数,push之后的数组1,2,5,8,10
    for(var i=0;i<arguments.length;i++){
      sum +=arguments[i];
    }
    return sum;
  }
 console.log(add(1,2,5,8));
</script>
<body>
</body>
</html>

Running result:

Related recommendations:

Js multiple methods of converting pseudo arrays into standard arrays

javascript Pseudo array implementation methods_javascript skills

Code to convert HTMLCollection/NodeList/pseudo array into array in js_javascript skills

The above is the detailed content of Detailed explanation of JavaScript pseudo array usage. 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