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

How to try to add sticky effect to your CSS

Written in front I don’t know who first discovere...

How to use html2canvas to convert HTML code into images

Convert code to image using html2canvas is a very...

A brief discussion on the definition and precautions of H tags

Judging from the results, there is no fixed patte...

Detailed explanation of top command output in Linux

Preface I believe everyone has used the top comma...

How to implement draggable components in Vue

This article shares with you how to implement dra...

SQL query for users who have logged in for at least n consecutive days

Take 3 consecutive days as an example, using the ...

Detailed installation process of MySQL5.6.40 under CentOS7 64

MySQL5.6.40 installation process under CentOS7 64...

Mysql queries the transactions being executed and how to wait for locks

Use navicat to test and learn: First use set auto...

Vue+openlayer5 method to get the coordinates of the current mouse slide

Preface: How to get the coordinates of the curren...

Solution to "Specialized key was too long" in MySQL

Table of contents Solution 1 Solution 2 When crea...

Three ways to achieve background blur in CSS3 (summary)

1. Normal background blur Code: <Style> htm...

A MySQL migration plan and practical record of pitfalls

Table of contents background Solution 1: Back up ...

Build a Docker private warehouse (self-signed method)

In order to centrally manage the images we create...

Cross-database association query method in MySQL

Business scenario: querying tables in different d...