Javascript,地图返回未定义 [英] Javascript, map returns undefined
问题描述
因此,我有24个人"对象,这些对象是使用名称"数组创建的,因此花花公子"名称在重复; 接下来,我创建了一个函数,用于将一些随机数与对象id-s进行比较,如果它们相等,那么我将尝试创建与该id一起使用的新的人员姓名数组.
So I have 24 "person" objects, which I created using "names" array, so that "dude" names are repeating; Next I made a function that compares some random numbers to object id-s, and if they are equal,then I am trying to make new array of person names that go with that id.
(对不起,如果听起来太复杂,但是我真的不明白为什么我的 map方法无法正常工作.)
(I'm sorry if this sounds too complicated, but I really don't understand why my map method doesn't work.)
这里有2个版本的代码. 第一个作品可以满足我的要求.
Here 2 versions of my code. The first one works, and does what I want.
var names = ["jim", "jack", "aaron", "hugh", "jeff", "cameron", "allen", "charlie"];
var len = 3,
arr1 = [],
counter = 1;
for (var i = 0; i < len; i++) {
names.forEach(name => {
arr1.push({
id: counter,
dude: name
});
counter++;
});
}
console.log(arr1);
function checkName(nums) {
var namesarr = [];
for (var i = 0; i < arr1.length; i++) {
nums.forEach(function(num) {
if (num === arr1[i].id) {
namesarr.push(arr1[i].dude);
}
});
}
return (namesarr);
};
console.log(checkName([1, 3, 6]));
但是在第二版中,我的地图函数返回未定义,我真的不明白为什么?!
But in second version, my map function returns undefined, and I really don't understand why?!
var names = ["jim", "jack", "aaron", "hugh", "jeff", "cameron", "allen", "charlie"];
var len = 3,
arr1 = [],
counter = 1;
for (var i = 0; i < len; i++) {
names.forEach(name => {
arr1.push({
id: counter,
dude: name
});
counter++;
});
}
console.log(arr1);
function checkName(nums) {
var namesarr;
for (var i = 0; i < arr1.length; i++) {
namesarr = nums.map(function(num) {
if (num === arr1[i].id) {
return arr1[i].dude;
}
});
}
return (namesarr);
};
console.log(checkName([1, 3, 6]));
推荐答案
您的map
函数不会为数组中的所有项目返回任何内容(由于if
),因此结果数组中的某些值将是undefined
.
Your map
function doesn't return something for all the items in the array (because of the if
) so some values in the result array will be undefined
.
此外,您的map
处于循环遍历arr1
的循环内,因此对于该循环的每次迭代,数组namesarr
都会被覆盖.因此,map
就像仅应用于arr1
中的最后一个元素,因此,如果nums
包含N
元素,则namesarr
至少将具有N - 1
undefined
值( N - 1
如果arr1
的最后一个对象与nums
匹配,则N
如果不匹配).
Plus, your map
is inside a loop that loops over arr1
, so for each iteration of that loop, the array namesarr
get overridden. So the map
will be as if it was applied only for the last element in arr1
, thus if nums
contain N
elements then namesarr
will have at least N - 1
undefined
values in it (N - 1
if the last object of arr1
matches nums
, N
if not).
使用 reduce
而不是map
:
function checkName(nums) {
return arr1.reduce(function(namesarr, obj) { // for each object obj in the array arr1
if(nums.indexOf(obj.id) !== -1) { // if the object's id is in the array nums
namesarr.push(obj.dude); // then add the object's dude to the array namesarr
}
return namesarr;
}, []); // the empty array to initialize namesarr
}
这篇关于Javascript,地图返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!