[英]How can I force a string of an integer to behave like a string when using it to deindex an associative array in node?
我有以下代碼:
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);
提供輸出:
[ <9 empty items>, true ]
[ <9 empty items>, true ]
[ <9 empty items>, true ]
換句話說,當將字符串int_str
用作數組arr
的鍵時,它的行為類似於數字10,而不是字符串“ 10”,並且9個空單元格在11號后面初始化。 盡管使用toString()
或嘗試使用+ ""
將其強制變為字符串,但toString()
發生這種情況。
我可以強制其像字符串一樣運行的唯一方法是附加一個實際字符,如int_str + "."
。 不過,這對我來說不是一個實際的解決方案。
使用Map
而不是array []
,只需避免這種廢話...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
地圖采用字符串,數字,對象和符號,並且不修改其鍵類型。
如果希望能夠將字符串作為真正的“鍵”傳遞,則不能使用數組,因為數組僅將非數字整數作為其索引。
如果將字符串作為索引器傳遞給數組,則會嘗試將該字符串轉換為非負整數,如果成功,則該數字索引將位於數組內。 如果不是,並且您正在設置一個值,則不會在數組中添加新項目。 您將在Array實例上創建一個新屬性,並且在枚舉數組時不會顯示該值。
例子:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.