通过数字索引创建数组而不推入数组

Create Array through Index of Numbers Without Pushing into Array

本文关键字:数组 创建 数字 索引      更新时间:2023-09-26

我有一个数组

var nums = [1,2,4];

我还有另一个阵列,里面挤满了

var people = [
    { name: 'Adam',      email: 'adam@email.com',      age: 12, country: 'United States' },
    { name: 'Amalie',    email: 'amalie@email.com',    age: 12, country: 'Argentina' },
    { name: 'Estefanía', email: 'estefania@email.com', age: 21, country: 'Argentina' },
    { name: 'Adrian',    email: 'adrian@email.com',    age: 21, country: 'Ecuador' },
    { name: 'Wladimir',  email: 'wladimir@email.com',  age: 30, country: 'Ecuador' },
];

我想创建一个基于nums变量作为people变量索引的变量。

// With the nums array I take each value and set it as the value of the new variable
// This is my expected output. Although this is line of code is not possible since the nums variable will be unique each time the code run.
var select_people = [people[1], people[2], people[4]];

我无法创建一个空数组,然后像这样将每个元素推入select_people数组。

// This will not do for me
var select_people = [];
for(var i = 0; i < nums.length; i++) {
  select_people.push(people[nums[i]])
}

我的问题是。如何编写此代码,以便在不必将值推入数组的情况下分配select_people变量?

如果你想要简洁,那么你可以尝试:

var selectPeople = people.filter(function(k, i) { return nums.indexOf(i) >= 0; });

同样,你可以这样做(我实际上更喜欢这样):

var selectPeople = nums.map(function(k) { return people[k]; });

注意:这只适用于现代浏览器。

然而,我想不出在许多情况下使用push不是最佳选择。

如果是命名冲突,您可以始终将其封装在临时函数中(适用于所有浏览器):

var selectPeople = (function() {
    var temp = [];
    for (var i = 0; i < nums.length; ++i) temp.push(people[nums[i]]);
    return temp;
})();

这基本上消除了任何命名冲突(例如,selectPeople不是真正的数组时的冲突,因为它缺少push方法)。

您尚未在for循环中初始化i变量:

这应该有效:

var select_people = [];
for(var i = 0; i < nums.length; i++) {
   select_people.push(people[nums[i]])
}

实现相同结果的另一种方法。

var people = [
    { name: 'Adam',      email: 'adam@email.com',      age: 12, country: 'United States' },
    { name: 'Amalie',    email: 'amalie@email.com',    age: 12, country: 'Argentina' },
    { name: 'Estefanía', email: 'estefania@email.com', age: 21, country: 'Argentina' },
    { name: 'Adrian',    email: 'adrian@email.com',    age: 21, country: 'Ecuador' },
    { name: 'Wladimir',  email: 'wladimir@email.com',  age: 30, country: 'Ecuador' },
];
var nums = [1,2,4];
var j = [];
for(var i = 0, l = nums.length; i < l; i++) {
  j.push(JSON.stringify(people[nums[i]]));
}
j = '[' + j.join(',') + ']';
var selectPeople = JSON.parse(j);
console.log(selectPeople);

for(x=0;x<nums.length;x++){
    alert(people[nums[x]]['name']);
    // or you can define your select_people here with people[nums[x]]
    // yes, you get people[1], people[2] and people[4]
    // but, your first people is "Adam", and people[1] is "Amalie"
}

因此,如果你想让第一个"nums"值为"1"的人,只需进行

for(x=0;x<nums.length;x++){
    alert(people[nums[x]-1]['name']);
    // or you can define your select_people here with people[nums[x]-1]
    // yes, you get people[0], people[1] and people[3]
    // your first people is "Adam", and people[0] is "Adam"
}