JavaScript: Functional mapping?
Is there a more succinct way to write this?
var me = {};
for (var i in you) {
me[i] = you[i];
}
(where you
is an arbi开发者_如何学Ctrarily-lengthed JavaScript array)
In other words, given the input of:
var you = [
"what",
"r",
"u"
];
The output, me
, becomes:
me = {
0: "what",
1: "r",
2: "u"
};
Like, a one-liner that uses some functional method?
Why do you want to do this? Arrays in JavaScript are Objects, except with some additional properties like slice
, splice
, push
and length
.
Internally, Arrays and Objects are stored exactly in the same way: e.g. array[0]
is the same as array["0"]
, or object["0"]
(unlike in other languages where adjacent array indices are in fact in adjacent memory - array "indices" are simply converted into strings in JavaScript).
So, if you just want to copy the data, then this will suffice:
me = you.slice(); // me is a copy of you, but is still an array
Or, if you really want some sort of mapping functionality, then underscore.js provides a whole collection of functional programming tools for your perusal.
There is no built-in function that does what you ask, however some of the widely used javascript libraries like jQuery provide such a function. In jQuery's case: jQuery.extend()
Usage:
var me = {};
jQuery.extend(me,someObject);
//or, equivalently -
var me2 = jQuery.extend({},someObject);
jQuery has an extend()
function (documentation here). Your code would look like this:
var me = {};
var you = ["what", "r", "u"];
$.extend(me, you);
This would allow you to do things like:
alert("Second element: " + me[1]);
It's a little odd, but I think it's what you're looking for.
I saw what you were trying to achieve with your string formatter. Instead of answering your original question of coming up with a concise implementation of one portion of it, I'll suggest a concise (and more flexible) implementation for the whole thing:
String.prototype.format = function () {
var args = arguments;
return this.replace(/\{(?:(\d+)|(\w+))\}/g, function (s, idx, prop) {
return prop && args[0]
? args[0][prop]
: args[idx];
});
};
When you have a number n
inside a token "{n}"
, it uses the n-th argument for replacement. Otherwise, for non-numerical keys, it picks the corresponding property of the first argument.
For example:
"I have {1} {name}s in my basket.".replace({ type: "fruit", name: "eggplant" }, 4);
Returns:
"I have 4 eggplants in my basket."
The underscore.js library also has a basic extend function.
var me = _({}).extend(you)
or
var me = {}
_(me).extend(you)
or
var me = {}
_.extend(me, you)
精彩评论