检查变量是否存在于数组的数组中

Check if variable exists in array of arrays

本文关键字:数组 变量 是否 存在 于数组 检查      更新时间:2023-09-26

我需要得到数组id,并把这个id号在var pointerid = (id number from array);
我使用以下代码来存储来自元素的点击id:

jQuery('a').click(function(){
    var clickedId= $(this).attr("id");

现在我想搜索如果'element': '等于' clickdid ',如果是,得到数组id。例如:
clickedId= test
wp_button_pointer_array[1] = {'element': 'test'
所以这里'element': 'test' = clickedId (test)然后给我数组id。这里的数组id是1

 var wp_button_pointer_array = new Array();
 wp_button_pointer_array[1] = {
     'element' : 'wp-button-pointer',
     'options' : {
         'content': 'The HTML content to show inside the pointer', 
         'position': {'edge': 'top', 'align': 'center'} 
     } 
 }; 
 wp_button_pointer_array[2] = { 
     'element' : 'some-element-id', 
     'options' : { 
         'content': 'The HTML content to show inside the pointer', 
         'position': {'edge': 'top', 'align': 'center'} 
     }
};

我真的不确定我理解你的问题,但这是你想做的吗?

function findElementIdByName(arr, name) {
  for (var i = 0; i < arr.length; i++)
    if (arr[i].element == name)
      return i;
  return -1; //not found
}
//example call with your data
var eleId = findElementIdByName(wp_button_pointer_array, 'some-element-id');

边注:数组索引在javascript中从0开始,你可以使用new array(),但由于javascript解释器

中的词法解析,[]稍微快一些(平均80ms)。
var wp_button_pointer_array = [
    {
        'element' : 'wp-button-pointer',
        'options' : {
            'content': 'The HTML content to show inside the pointer',
            'position': {'edge': 'top', 'align': 'center'}
        }
    },
    {
        'element' : 'some-element-id',
        'options' : {
            'content': 'The HTML content to show inside the pointer',
            'position': {'edge': 'top', 'align': 'center'}
        }
    }
];

$('a').on('click', function(){
    var clickedId = $(this).attr("id");
    for(var i = 0; i < wp_button_pointer_array.length; i++ ) {
        if(wp_button_pointer_array[i].element === clickedId) {
            //do staff with wp_button_pointer_array[i]
        }
    }
});

这将返回包含给定element属性的索引。

function getIndexByElementId(elementArray, elementId) {
    var i, len;
    for(i = 0, len = elementArray.length; i < len; i++) {
        if(elementArray[i].element === elementId) {
            return i;
        }
    }
}