2016-09-12 2 views
-3

다음과 같은 배열이 있습니다. this.itemsgroupcustomer.indexOf("Perorangan")을 사용하면 -1이 반환됩니다. 왜 이것이 잘못된지 전혀 모르겠다. 도와주세요.{nativescript} indexOf 배열

viewModel.itemsgroupcustomer = [ 
     {title: "Perusahaan"}, 
     {title: "Perorangan"} 
    ]; 
+0

배열에 'Perorangan' 문자열이 포함되어 있지 않기 때문에. – zerkms

답변

3

입니다 findIndex 메소드 사용 -

viewModel.itemsgroupcustomer.findIndex(x=>x.title==='Perorangan'); 
+0

Yups @chetan, 이것은 더 간단합니다. 감사 :) –

2

사용 Array.prototype.find는 대신, 테스트 통과하는 요소 반환

const arr = [ 
 
    {title: "Perusahaan"}, 
 
    {title: "Perorangan"} 
 
] 
 
console.log(arr.find(el => el.title === 'Perorangan'))

당신은 다음 배열에 인덱스를 찾기 위해 반환 값을 사용할 수 있습니다

const arr = [ 
 
    {title: "Perusahaan"}, 
 
    {title: "Perorangan"} 
 
] 
 
const filteredElement = arr.find(el => el.title === 'Perorangan') 
 
console.log(arr.indexOf(filteredElement))


UPDATE : 사용자 @zerkms으로

거기에 지적 한 한 단계 위의 수행 방법에 내장, 그것은 Array.prototype.findIndex

const arr = [ 
 
    {title: "Perusahaan"}, 
 
    {title: "Perorangan"} 
 
] 
 
console.log(arr.findIndex(el => el.title === 'Perorangan'))

+1

거기에'Array.prototype.findIndex'가 있습니다. – zerkms

+0

많은 @mauricio에게 감사드립니다. 어떻게 배열 작업을 할 수 있습니까? 때로는 배열 세계에서 길을 잃어 버렸습니다. 여기 내 온라인 코드'this.itemsgroupcustomer.indexOf (this.itemsgroupcustomer.find (el => el.title === "Perorangan"))''이 있습니다. 그것은 1입니다. yay –