我有以下对象,如果名称与变量匹配,我想要实现的是获取主题的索引。

例如:我在视图中循环,并且如果我的任务(something1)变量与name元素匹配,则返回对象的索引。

通过给定的示例,我应该将结果设为0,

var views = [

    {
        name: "something1",
        type: something1,
        columns: something1
    },

    {
        name: "something2",
        type: something2,
        columns: something2
    },

    {
        name: "something3",
        type: something3,
        columns: something3
    }

];


var task = 'something1';

$.each(views, function(index, value) {

    if (value.name = task) {
        alert(index);
    }

});

最佳答案

您实际上不需要jQuery:

参见:http://jsfiddle.net/enNya/2/

var views = [
    {
        name: "something1",
        type: "something1",
        columns: "something1"
    },
    {
        name: "something2",
        type: "something2",
        columns: "something2"
    }
];

var task = 'something2';

// Set a var and maintain scope
var i;

// Loop each element of the array
for (i = 0; i < views.length; i++) {
    // If the X = Y the stop looping
    if (views[i].name == task) {
        break;
    }
}

// Check if it was not found
i = i == views.length ? false : i;

// Log the result
console.log(i);

09-25 21:08