如何使用 Prototype JavaScript 框架从数组创建哈希?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3797951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:16:37  来源:igfitidea点击:

How do I create a Hash from an Array using the Prototype JavaScript framewor?

javascriptprototypejs

提问by denisjacquemin

I've an Array ['red', 'green', 'blue']

我有一个数组 ['red', 'green', 'blue']

I want to create a new Hash from this Array, the result should be

我想从这个数组创建一个新的哈希,结果应该是

{'red':true, 'green':true, 'blue':true}

What is the best way to achieve that goal using Prototype?

使用 Prototype 实现该目标的最佳方法是什么?

回答by Felix Kling

Just iterate over the array and then create the Hash:

只需遍历数组,然后创建哈希:

var obj  = {};
for(var i = 0, l = colors.length; i < l; i++) {
    obj[colors[i]] = true;
}
var hash = new Hash(obj);

You can also create a new Hash object from the beginning:

您还可以从头开始创建一个新的 Hash 对象:

var hash = new Hash();
for(var i = 0, l = colors.length; i < l; i++) {
    hash.set(colors[i], true);
}

I suggest to have a look at the documentation.

我建议看看文档

回答by Mike Fabrikant

This functional javascript solution uses Array.prototype.reduce():

这个功能性的 javascript 解决方案使用Array.prototype.reduce()

['red', 'green', 'blue']
.reduce((hash, elem) => { hash[elem] = true; return hash }, {})

Parameter Details:

参数详情

  • callback ? Function to execute on each value in the array.
  • initialValue ? Object to use as the first argument to the first call of the callback.
  • 打回来 ?对数组中的每个值执行的函数。
  • 初始值 ?用作回调第一次调用的第一个参数的对象。

The third argument to the callback is the index of the current element being processed in the array. So if you wanted to create a lookup table of elements to their index:

回调的第三个参数是数组中正在处理的当前元素的索引。因此,如果您想为其索引创建元素查找表:

['red', 'green', 'blue'].reduce(
  (hash, elem, index) => {
    hash[elem] = index++;
    return hash
  }, {});

Returns:

返回:

Object {red: 0, green: 1, blue: 2}

回答by denisjacquemin

Thanks all

谢谢大家

here is my solution using prototypejsand inspired by Felix's answer

这是我使用prototypejsFelix 的答案并受其启发的解决方案

var hash = new Hash();
colors.each(function(color) {
  hash.set(color, true);
});