简体   繁体   中英

How can I force a string of an integer to behave like a string when using it to deindex an associative array in node?

I have the following code:

var arr = [];

var int_str = "9";    
arr[int_str] = true;
console.log(arr);    
arr[int_str + ""] = true;
console.log(arr);    
arr[int_str.toString()] = true;
console.log(arr);

Giving the output:

[ <9 empty items>, true ]
[ <9 empty items>, true ]
[ <9 empty items>, true ]

In other words, when the string int_str is used as the key to the array arr , it behaves like the number 10, rather than the string "10", and 9 empty cells initialize behind the 11th. This happens despite using toString() , or trying to force it in to becoming a string with + "" .

The only way I can force this to behave like a string is to append an actual character like int_str + "." . That's not a practical solution for me though.

Use a Map instead of an array [] and simply avoid that nonsense...

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Maps take strings, numbers, objects, and symbols and do not modify their key types.

If you want to be able to pass a string as a true "key", then you can't use an Array as Arrays only take non-numeric whole numbers as their indexes.

If you pass a string as an indexer to an array, an attempt to convert that string to a non-negative whole number is made and, if successful, that numeric index is located within the array. If not, and you are setting a value, you won't be adding a new item to the array. You'll be creating a new property on the Array instance and that value won't show up when you enumerate the array.

Examples:

 let myArr = [1,2,3,4,5,6,7,8,9]; console.log("Arrays:"); console.log(myArr[5]); // 6 console.log(myArr["5"]); // 6 console.log(myArr["ten"]); // undefined - Arrays don't take keys // Objects: let myObj = { one:1, two:2, three:3, 4:4, five:5 }; console.log("Objects:"); console.log(myObj["4"]); // 4 console.log(myObj[4]); // 4 - The number is treated as a string because keys are strings console.log(myObj["five"]); // 5 console.log(myObj[2]); // undefined - objects don't take indexes and there is no key of 2 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM