简体   繁体   English

如何在javascript中使用数组的值获取数组的索引?

[英]How to get index of array using its value in javascript?

Hi I am new to javascript. 嗨,我是javascript新手。 I want to get the index of array using its value and append new element into that array. 我想使用其值获取数组的索引,并将新元素附加到该数组中。 Here is my array: 这是我的数组:

var testArray=[];

testArray.push({"key1":"value1","key2":"value2"});
testArray.push({"key1":"value11","key2":"value22"});

Now I want to get the index of "value11" and also append new element as "key3":"value33" in the same index as below: 现在,我要获取“ value11”的索引,并在以下相同的索引中附加新元素作为“ key3”:“ value33”:

testArray.push({"key1":"value11","key2":"value22","key3":"value33"});

Please explain. 请解释。 Thanks in advance... 提前致谢...

var testArray=[];

testArray.push({"key1":"value1","key2":"value2"});
testArray.push({"key1":"value11","key2":"value22"});

var filtered = testArray.filter(function(item) {
    if (item.key1 == 'value11') {
        item.key3 = 'value33';
        return true
    }
    return false;
});

http://jsfiddle.net/XUzJw/ http://jsfiddle.net/XUzJw/

Here's the simple answer: 这是简单的答案:

var testArray = [];

testArray.push();
testArray.push();

// loop through every element of the array
for(var i = testArray, l = testArray.length; i < l; i++){
  // grab this particular object
  var obj = testArray[i];

  // see if key1 is equivalent to our value
  if(obj.key1 == 'value11'){
    // if so, set key3 to the value we want for this object
    obj.key3 = 'value33';
    break;    
  }
}

The better answer looks more like this: 更好的答案看起来像这样:

var testArray = [
  {
    "key1" : "value1",
    "key2" : "value2"
  },
  {
    "key1" : "value11",
    "key2" : "value22"
  }
];

function findAndSwap(list, comparator, perform){
  var l = list.length;
  while(l--) if(comparator(list[l], l, list)) perform(list[l], l, list);
}

function checkProp(prop, value){ return function(obj){ return obj[prop] === value } }
function addProp  (prop, value){ return function(obj){ obj[prop] = value          } }

findAndSwap(testArray, checkProp('key1', 'value11'), addProp('key3', 'value33'));

you can try something like. 您可以尝试类似的方法。 This code will work even when you do not have the key names. 即使您没有键名,此代码也将起作用。 It finds key-names on basic of value. 它基于值的基础查找键名。 Had also added it to jsFiddle http://jsfiddle.net/rTazZ/2/ 还已经将其添加到jsFiddle http://jsfiddle.net/rTazZ/2/

var a = new Array(); 
a.push({"1": "apple", "2": "banana"}); 
a.push({"3": "coconut", "4": "mango"});

GetIndexByValue(a, "coconut");

function GetIndexByValue(arrayName, value) {  
var keyName = "";
var index = -1;
for (var i = 0; i < arrayName.length; i++) { 
   var obj = arrayName[i]; 
        for (var key in obj) {          
            if (obj[key] == value) { 
                keyName = key; 
                index = i;
            } 
        } 
    }
    //console.log(index); 
    return index;
} 

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

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