Home >Web Front-end >JS Tutorial >JavaScript pseudo array usage examples
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. This article describes the use of JavaScript pseudo-arrays with examples. I hope it can help everyone.
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 an 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>
operation result:
Convert pseudo array to 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>
Running results:
Related recommendations:
Detailed explanation of JavaScript pseudo array usage
js will pseudo array Various methods of converting arrays into standard arrays
javascript Pseudo-array implementation methods_javascript skills
The above is the detailed content of JavaScript pseudo array usage examples. For more information, please follow other related articles on the PHP Chinese website!