繁体   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