誰能指導我如何在一個陣列中找到一個元素?
對于存在的元素,我總是得到假的。
謝謝。
謝謝你。
arr = new Array;
arr.push({x: "a"/span>, y: 1})。)
arr.push({x: "b"/span>, y: 2})。)
arr.push({x: "c"/span>, y: 3})。)
elem = {x: "c"/span>, y: 3}。
if (arr.includes(elem)){
console.log('true')。
} else {
console.log('false')。
}
uj5u.com熱心網友回復:
你要找的是{x: "c", y: 3}物件,并且它永遠不會等于任何其他物件,因為{} !== {}。
記住:物件是通過reference進行比較的,但是基元是通過其value進行檢查的。
在你的代碼中,你正在檢查一個物件的參考和另一個參考,這是不相等的,所以它記錄了false。
如果有數字陣列,那么你應該使用includes作為:
。const arr = [10, 20, 30] 。
if(arr.includes(20) console.log("true") 。
else console.log("false");
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
你可以使用find來查找陣列中的元素
。 。const arr = new Array()。
arr.push({ x: "a"/span>, y: 1 })。)
arr.push({ x: "b"/span>, y: 2 })。)
arr.push({ x: "c"/span>, y: 3 })。)
const elem = { x: "c"/span>, y: 3 }。
if (arr.find((o) => o. x === elem.x && o.y ===elem.y) {
console.log("true") 。
} else {
console.log("false")。
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
由于你使用的是2D陣列,我相信你的物件在X和Y上都是一樣的,所以我建議你做一個這樣的函式,以便在你的代碼中進一步使用
。 。arr = new Array;
arr.push({x: "a"/span>, y: 1})。)
arr.push({x: "b"/span>, y: 2})。)
arr.push({x: "c"/span>, y: 3})。)
elem = {x: "c"/span>, y: 3}。
console.log(findXY(arr,elem) )
function findXY(arr,val){
return arr.find(each=> {
return each.x == val.x && each.y == val.y.
})
}
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/322445.html
標籤:
