简体   繁体   English

Javascript 比较索引与数组值

[英]Javascript Compare Index with Array Value

I have a main array, and an object that contains an array of items.我有一个主数组和一个包含项目数组的对象。 I want to see if the object that contains items matches the main array index.我想查看包含项目的对象是否与主数组索引匹配。 If a match, then write to the console.如果匹配,则写入控制台。

var mainItems = [0,1,2,3,4,5,6,7,8,9,10,"car", "boat", "truck", "plane"];
var nonStandardItems =
{
    "items": [
        {

            "value": "8",
            "code": "8ic"
        },
        {
            "value": "boat",
            "code": "10bt"
        }
    ],

}

if( nonStandardItems.items.slice(-1)[0].value == mainItems.indexOf(nonStandardItems.items.slice(-1)[0].value)  ){
    console.log("you are right");
}

However, I only get a value of -1, and an error.但是,我只得到 -1 的值和错误。 What am I missing?我错过了什么?

EDIT I am pulling data from a different data sources, all containing junk data.编辑我从不同的数据源中提取数据,所有数据都包含垃圾数据。 However, the last item in the junk data array is the item I need.但是,垃圾数据数组中的最后一项是我需要的项目。

I want to check if the results from my api request match an "expected" or "standard" set of data.我想检查我的 api 请求的结果是否与“预期”或“标准”数据集匹配。 For example, my nonStandardItems object is an example of what I get back from the api.例如,我的 nonStandardItems 对象是我从 api 返回的示例。

I want to parse it, and check to see if the LAST item in the items array has a value that matches the index of my standard items array.我想解析它,并检查 items 数组中的最后一项是否具有与我的标准 items 数组的索引匹配的值。 My junk items array contains numeric and text data, but the last item will always have either a numerical or textual code that I expect.我的垃圾项目数组包含数字和文本数据,但最后一个项目将始终具有我期望的数字或文本代码。

The example was contrived and rushed, so I apologize for the spelling, syntactical and explanation mistakes.这个例子是人为的和仓促的,所以我为拼写、语法和解释错误道歉。 The error the console threw was that nonstandardItems.items[-1].value did not exist.控制台抛出的错误是 nonstandardItems.items[-1].value 不存在。

Use filter():使用过滤器():

if (nonStandardItems.items.filter(v => mainItems.indexOf(v.code) == v.value).length > 0) {
    console.log("you are right")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM