我有一个数组
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
变量而无需将值推送到数组中?
答案 0 :(得分:1)
如果您想要简洁,那么您可以尝试:
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
方法。)
答案 1 :(得分:0)
您尚未在i
循环中初始化for
变量:
这应该有效:
var select_people = [];
for(var i = 0; i < nums.length; i++) {
select_people.push(people[nums[i]])
}
答案 2 :(得分:0)
获得相同结果的另一种方法。
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);
答案 3 :(得分:0)
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"
}
所以,如果你想带第一个名为“1”的“nums”的人,那就去做
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"
}