JavaScript“地图"功能 [英] JavaScript "map" Function
问题描述
查看地图功能在JavaScript中,我在这里做什么错了?
Looking at the map function in JavaScript, what am I doing wrong here?
// input: [{name: "Kevin"}, {name: "Bob"}];
// output: [{"Kevin" : 0}, {"Bob" : 1}];
var map = function(arr, property) {
var i = 0;
var m = arr.prototype.map(makeKv);
// input: {name: "Kevin"}
// output: {"Kevin" = i} // GLOBAL
function makeKv(item) {
return {item: i++};
};
console.log("m : " + m);
}
此外,如果您能帮助我,请也摆脱 global .
Also, if you could help please me get rid of the global too.
推荐答案
这里有一些问题:
首先
var m = arr.prototype.map(makeKv);
您在这里不需要 prototype
.仅在使用构造函数时使用它,例如 Array.prototype.map
.在这里,您只需要执行 arr.map
.
You don't need prototype
here. You only use that when you are using the constructor, like Array.prototype.map
. Here, you just need to do arr.map
.
第二,
function makeKv(item) {
return {item: i++};
};
您永远不会在任何地方声明 i
.如何将一个添加到不存在的对象中.在此之前,您需要具有 var i = 0;
.
You never declare i
anywhere. How can you add one to something that doesn't exist. You need to have var i = 0;
before this.
最后, return {item:i ++};
将创建一个名为 literally "item"
的键.您需要先声明对象( var ret = {};
),然后使用 [item]
设置值.
Finally, return {item: i++};
will make a key called literally "item"
. You need to declare the object first (var ret = {};
), then use [item]
to set the value.
Array.map
的回调函数将数组中的元素作为第一个参数传递,因此 item
将是一个对象.您需要执行 item [property]
来获取所需的值.
Array.map
's callback is passed the element in the array as the 1st parameter, so item
will be an object. You need to do item[property]
to get the value you want.
P.S.不要在您的 console.log
中执行"m:" + m
,这会连接字符串,从而将 m
转换为字符串.使用,
代替: console.log("m:",m);
P.S. Don't do "m : " + m
in your console.log
, that will concat strings, thus converting m
to a string. Use ,
instead: console.log("m : ", m);
因此,一起尝试:
var map = function(arr, property) {
var i = 0;
var m = arr.map(makeKv);
function makeKv(item) {
var ret = {};
ret[item[property]] = i++;
return ret;
};
console.log("m : ", m);
}
演示: http://jsfiddle.net/FgdSj/3/
编辑: Array.map
的回调传递了数组中的索引作为第二个参数,因此 var i = 0;
这里不需要:
EDIT: Array.map
's callback is passed the index in the array as the 2nd parameter, so var i = 0;
isn't needed here:
var map = function(arr, property) {
var m = arr.map(makeKv);
function makeKv(item, index) {
var ret = {};
ret[item[property]] = index;
return ret;
};
console.log("m : ", m);
}
演示: http://jsfiddle.net/FgdSj/5/
这篇关于JavaScript“地图"功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!