簡體   English   中英

在JavaScript中是否有更好的方法可以做到這一點? 使用while進行數組搜索

[英]Is there a better way to do this in JavaScript? Array search using while

我正在考慮改進以下代碼的方法,主要是通過最小化代碼行,同時還要讓讀者清楚代碼的作用。 我可以在下面的示例中以某種方式使用indexOf()嗎?

var events = myArray.data.items;

data = null;
found = false;
counter = 0;
if (selectedValue != "") {
    while (!found && counter < events.length) {
        //notice there's an extra layer of objects for each object in the array
        if (events[counter].data.Event_ID == selectedValue) { 
            data = events.items[counter].data;
            //do stuff
            found = true;
            break;
        }
        counter++;
    }
}

您可以使用some()方法:

var data = null;
var found = events.some(function (event) {
    return event.data.Event_ID == selectedValue ? ((data = event.data), true) : false;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM