Detailed explanation of data type issues in JS array index detection

Detailed explanation of data type issues in JS array index detection

When I was writing a WeChat applet project, there was a "city selection" function in it. The author used the <picker-view> component. This component is special because its value attribute is specified in array format. For example: value="[1]" .

Because I didn't understand the JS variable type conversion at the time, I wrote a few lines of judgment in the code: (This is rigorous)

let val_one=typeof this.data.pIndex=="number"?[this.daya.pIndex]:this.data.pIndex

(: The access elements in the project are dynamic!

The above is because we want the subscript to dynamically follow the user's selection and be fed back to value attribute in wxml for display.

But before that, we need to make a judgment - because some areas are provincial cities or municipalities, and we need to prevent users from "stupid operations", such as pulling up or pulling out suddenly. At this time, the WeChat applet will report an error that the corresponding data cannot be found:

let length = placeArray[val_one].sub.length
if(val[0]>=length){
 val=[length-1]
}else if(val[0]<0){
 val=[0]
}

Later, when I went back to optimize the code for this project, I found that this (converting arrays to numbers when forcing, and converting numbers to arrays when giving feedback) was actually unnecessary:

detail

JavaScript seems to have its own "unique" way of processing data, but the author has not found any relevant information yet~~

How to determine whether a value can be used as an array subscript (index)

But one thing is certain: assigning values ​​to integer property keys is a special case of arrays, because they are handled differently from non-integer keys. To determine whether a property can be used as an array index, the author found a passage in the ES6 specification document:

Currently a string property name P is an array index only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1 .

This operation can be implemented using JS as follows:

function toUint32(value){
	return Math.floor(Math.abs(Number(value))) % Math.pow(2,32);
}
function isArrayIndex(key){
	let numericKey = toUint32(key);
	return String(numericKey) == key && numericKey < (Math.pow(2,32)-1);
}

The toUint32() function converts the given value to an unsigned 32-bit integer using the algorithm described in the specification. isArrayIndex() function first converts the key to a uint32 structure, and then performs two comparisons (after toString() , check if it is not equal to the original number and whether it is less than 2^32-1 ).

With this foundation, we can simply imitate the behavior of new Array() based on this - the most important thing is the description of length:

array_length

function createArray(length=0){
	return new Proxy({ length },{
		set(trapTarget,key,value){
			let currentLength=Reflect.get(trapTarget,"length");
			if(isArrayIndex(key)){
				let numericKey = Number(key);
				if(numericKey >= currentLength){
					Reflect.set(trapTarget,"length",numericKey+1);
				}
			}else if(key === "length"){
				if(value < currentLength){
					for(let index=currentLength-1;index>=value;index--){
						Reflect.deleteProperty(trapTarget,index);
					}
				}
			}
			// No matter what type the key is, this code must be executed return Reflect.set(trapTarget,key,value);
		}
	});
}

Experiment with this:

myArray_test

Summarize

This is the end of this article about the detailed explanation of data type issues in JS array index detection. For more information about data types in JS array index detection, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript type detection method example tutorial
  • Detailed explanation of data types in JavaScript and how to detect data types
  • Detailed explanation of data type detection methods in javascript
  • Summary of js data type detection
  • js learning summary_Four methods based on data type detection (must read)
  • Summary of JS methods for detecting array types
  • Summary of several ways to detect data types in javascript
  • Summary of JavaScript basic data types and common methods of type detection
  • Summary of several ways to detect data types in JS and their advantages and disadvantages
  • JS regular expression matching detection of various numeric types (digital verification)
  • How to detect various types of JavaScript
  • JavaScript type detection: defects and optimization of typeof and instanceof
  • JavaScript learning notes: Detecting client type (engine, browser, platform, operating system, mobile device)
  • Javascript implements detection of client type code package
  • JavaScript method to detect the type of file

<<:  Summary of 11 amazing JavaScript code refactoring best practices

>>:  How to use the WeChat Mini Program lottery component

Recommend

A brief discussion on browser compatibility issues in JavaScript

Browser compatibility is the most important part ...

How to view the docker run startup parameter command (recommended)

Use runlike to view the docker run startup parame...

Example code of vue custom component to implement v-model two-way binding data

In the project, you will encounter custom public ...

Detailed example of MySQL joint table update data

1.MySQL UPDATE JOIN syntax In MySQL, you can use ...

Interactive experience trends that will become mainstream in 2015-2016

The most important interactive design article in ...

js dynamically adds example code for a list of circled numbers

1. Add the ul tag in the body first <!-- Unord...

Summary and practice of javascript prototype chain diagram

Table of contents Prototype chain We can implemen...

Linux View File System Type Example Method

How to check the file system type of a partition ...

How to create a stored procedure in MySQL and add records in a loop

This article uses an example to describe how to c...

Nginx configuration file detailed explanation and optimization suggestions guide

Table of contents 1. Overview 2. nginx.conf 1) Co...

Analysis of the use and principle of Docker Swarm cluster management

Swarm Cluster Management Introduction Docker Swar...

How to underline the a tag and change the color before and after clicking

Copy code The code is as follows: a:link { font-s...