[課程提問] 關於本章節的for in部分

Lastor
Code 隨筆放置場
2 min readAug 12, 2019

(前略)

這個範例讓我驚呆了XD
JS居然會允許Array裡放入 ( key: value ) 這種格式的…. 值???
我剛才用Ruby測試了一下, Ruby中這種操作是不合法的

// 給Array賦予 (key: value)
x = ['a', 'b']
x[:foo] = 'hello'

// Error, no implicit conversion of Symbol into Integer

Ruby嚴格規定了Array的index只能是0, 1, 2…. 這些序列號,
如果非要自定義index名稱, 只能做一個雜湊塞進去

// (key: value) 形式永遠只能成立在雜湊中
x = ['a', 'b']
x[2] = {foo: 'hello'}
x // ["a", "b", {:foo=>"hello"}]

我以為JS也應該要是這個邏輯, Array就是Array, Objects就是Objects。
可是這個居然可以成立…..!?

// 給Array賦予 (key: value)
let x = [3, 5, 7]
x['foo'] = 'hello' // 同義 x.foo = 'hello'
x // [3, 5, 7, foo: 'hello']
x[3] // undefined

它跟這樣寫居然是不一樣的

// 給Array賦予 (key: value)
let x = [3, 5, 7]
x[3] = {foo: 'hello'}
x // [3, 5, 7, {foo: 'hello'}]
x[3] // {foo: 'hello'}

難怪Array的型別是Object

typeof x  // "object"

我真的驚呆了, 這樣for-in確實會call出非序列號的字串…..
我覺得這有點恐怖XD

--

--

Lastor
Code 隨筆放置場

Web Frontend / 3D Modeling / Game and Animation. 設計本科生,前遊戲業 3D Artist,專擅日本動畫與遊戲相關領域。現在轉職為前端工程師,以專業遊戲美術的角度涉足 Web 前端開發。