Home > Web Front-end > JS Tutorial > body text

What is a pseudo array in js

php中世界最好的语言
Release: 2020-09-04 15:32:29
Original
5123 people have browsed it

The pseudo-array in js means that you cannot directly call the array method or expect any special behavior of the length attribute, but you can still traverse them through the traversal method, typically the argument parameter of the function.

What is a pseudo array in js

This time I will bring you JS pseudo-array usagedetailed explanation, and notes on the use of JS pseudo-arrayWhat are they? The following is a practical case. Let’s take a look.

What is a pseudo array in Javascript?

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

1. Typical is the argument parameter of the function,
2. Like 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 sum of indefinite parameters.

nbsp;html>


<meta>
<title>伪数组</title>

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


Copy after login

operation result:

What is a pseudo array in js

Convert a pseudo array into a standard array

nbsp;html>


<meta>
<title>伪数组</title>

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


Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

The above is the detailed content of What is a pseudo array in js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
js
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