简体   繁体   English

在map方法中获取数组键

[英]Get array key in map method

I am comparing two arrays with each other in a function and want to return an array with the highest values at each array key. 我正在函数中比较两个数组,并希望返回每个数组键处具有最高值的数组。 In my function I have two parameters which both represent an array. 在我的函数中,我有两个参数都代表一个数组。

The arrays have the same length and their key values are normal index numbers 数组具有相同的长度,并且其键值为常规索引号

Now I just use a normal for loop: 现在,我只使用普通的for循环:

var array1 = [50, 30, 44, 8];
var array2 = [12, 44, 18, 9];

function createList(arr1, arr2){
    for(var x = 0; x < arr1.length; x++){
        arr1[x] = arr1[x] > arr2[x]?arr1[x]:arr2[x];
    }
    return arr1;
}

var highList = createList(array1, array2);

Now I know there are other possiblities of getting this result. 现在,我知道获得此结果还有其他可能性。 But what I was wondering whether you can get the current key in the map method and use that to compare it with another array. 但是我想知道您是否可以在map方法中获取当前键并将其与另一个数组进行比较。

Something in the line of: 符合:

var highList = array1.map(function(num){
    return num > array2[keyOfCurrentMap]?num:array2[keyofCurrentMap];
});
var highList = array1.map(function(num, keyOfCurrentMap){
    return num > array2[keyOfCurrentMap]?num:array2[keyofCurrentMap];
});

The second param passed into the callback for map is the key. 传递map的回调的第二个参数是关键。

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

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