Page 1 of 1

judge var isArray or isObject?

Posted: 07 May 2019, 02:12
by hyaray
I want a function "getType", Thanks!! :wtf: :wtf:

Code: Select all

getType([1,2]) ;return "Array"

Code: Select all

getType({"a":"aa", "b","bb"}) ;return "Object"

Re: judge var isArray or isObject?

Posted: 07 May 2019, 03:54
by Klarion
I do not know the real differencies between Array and Object in AHK

Re: judge var isArray or isObject?

Posted: 07 May 2019, 04:14
by jeeswg
Perhaps something like this for IsArray. If anyone can point out any improvements, please do.

Code: Select all

;requires AHK v1.1.29+
;has integer keys 1 to n with no gaps, or is an empty object
IsArray(oArray)
{
	local
	if !ObjCount(oArray)
		return 1
	if !(ObjCount(oArray) = ObjLength(oArray))
	|| !(ObjMinIndex(oArray) = 1)
		return 0
	for vKey in oArray
		if !(vKey = A_Index)
			return 0
	return 1
}

Re: judge var isArray or isObject?

Posted: 07 May 2019, 04:40
by evilC
arr.Length() == arr.Count() seems to detect sparse arrays

Re: judge var isArray or isObject?

Posted: 07 May 2019, 04:47
by jeeswg
You could have: non-integer key count = gap count.

Code: Select all

oArray := ["a", "b", "c"]
MsgBox, % oArray.Length() " " oArray.Count() ;3 3
oArray := {1:"a", 3:"c", x:"x"}
MsgBox, % oArray.Length() " " oArray.Count() ;3 3

Re: judge var isArray or isObject?

Posted: 07 May 2019, 04:52
by swagfag
well what is an array really. id probably check if the first element's key is at least >1 and then check if all elements' keys are numbers.

Re: judge var isArray or isObject?

Posted: 07 May 2019, 05:11
by jeeswg
'ARRAY'
- The AHK Array function creates objects with keys 1 to n, with no gaps.
- (Typically, arrays in programming languages are objects with keys 0 to n, with no gaps.)

AN AHK OBJECT CONTAINING INTEGERS ONLY
- It might be useful to be able to identify AHK objects where all the keys are integer keys, and where gaps are allowed. An AHK for loop lists integer keys first, so you could do a loop and check until you reach MaxIndex, and if there was at least one more key after that, that would be a non-integer key.

IS IT AN AHK OBJECT
- Here is a test to see if something is a basic AHK object:
type(v) for v1.1 - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=6&t=2306
ObjGetCapacity(x) != ""
- (The IsObject function checks if something is an object, not if it is an object capable of being created by the Object function.)
- (In AHK v1, Array() / [] / Object() / {}, use the same object type.)