# 檢查陣列元素是否存在的方法 #### indexOf 接受一個元素作為輸入參數。 1. 若存在的話會回傳該元素所在的索引值 2. 不存在的話回傳-1。 ``` javascript= let happyMood = ['flower', 'sky', 'sunshine']; happyMood.indexOf('flower'); // 0 happyMood.indexOf('sunshine'); // 2 happyMood.indexOf('math'); // -1 ``` #### hasOwnProperty() 會回傳是否有該屬性的布林值。 與`in`不同的地方是,`hasOwnProperty`不會檢查物件的原型鍊(prototype chain,或稱之為原型繼承),只會檢查該物件中所擁有的屬性鍵,類別定義時的方法是沒辦法檢測到,由原型繼承的方法也沒辦法檢測到。 (此處參考*https://eyesofkids.gitbooks.io/javascript-start-from-es6/content/part3/object.html*) 表達式: ``` obj.hasOwnProperty(prop) ``` Example: ``` javascript= let bread = ['bagel', 'toast', 'croissant']; 'toast' in bread; //true 'croissant' in bread; //true 'muffin' in bread; //false ``` #### in 使用in關鍵字 有的話回傳true,沒有的話回傳false。 ``` javascript= let animals = ['bear', 'tiger', 'fox']; 'bear' in animals; //true 'fox' in animals; //true 'leopard' in animals; //false ``` 效率上來說,用`undefined`判斷屬性值最快,或使用`hasOwnProperty`。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up