如何在函数式JavaScript中捕获对象的哈希?

如何在函数式JavaScript中捕获对象的哈希?,javascript,hash,functional-programming,Javascript,Hash,Functional Programming,我正在用JavaScript为现代浏览器编写一段代码。我不使用lodash或下划线,因为我们希望使库尽可能小 比如说, 如果url是这样的。http://something.com/hash=value 应用程序被配置为捕获密钥散列,那么结果就是这样。没什么特别的。我只是想知道是否有更好的方法或简单的方法来做到这一点 { 'hash': 'value' } 代码 var config = Object.assign({}, { capturedHashParams: ['hash']

我正在用JavaScript为现代浏览器编写一段代码。我不使用lodash或下划线,因为我们希望使库尽可能小

比如说,

如果url是这样的。http://something.com/hash=value 应用程序被配置为捕获密钥散列,那么结果就是这样。没什么特别的。我只是想知道是否有更好的方法或简单的方法来做到这一点

{
 'hash': 'value'
}
代码

var config = Object.assign({}, {
    capturedHashParams: ['hash']
});

var hashValue = '#hash=value1'.substr(1);

var capturedHashParams = {};
if (config.capturedHashParams && Array.isArray(config.capturedHashParams)) {
  var splitedHash = hashValue.split('=');
  if (splitedHash.length > 0) {
    var key = splitedHash[0] || '';
    var value = splitedHash[1] || '';
    if (key && value) {
      config.capturedHashParams.forEach(function(hp) {
        if (hp.toLowerCase().indexOf(key.toLowerCase()) > -1) {
          capturedHashParams[key] = value;
        }
      });
    }
  }
}

console.log(capturedHashParams);

你的问题有点模棱两可。似乎您希望从url哈希中提取键/值对,并作为JavaScript对象返回。我有点不确定是要提取所有键/值对,还是只提取配置对象中提供的键/值对。我也有点不确定,您是想要一个严格的函数式编程范例中的解决方案,还是只需要一个代码占用量小的简单解决方案。我假设是后者

捕获所有键/值对的简单方法:

var url='1〕http://something.com/hash=value&anotherHash=value'; //从url中提取键=值对 var params=url.split.pop.split'&'; //分配给数据对象 forvar data={},i=0,temp;i控制台日志数据 我想你在关注这样的事情:

var output = [];
var hashString = window.location.hash;
var hashArray = hash.split('&');

for(var index = 0; index < hashArray.length; index++){
  var text = hashArray[index];
  var tempArray= text.split('=');
  var object = {
    id: tempArray[0],
    value: tempArray[1]
  };
  output[index] = object;
}
[
  {
    id: "hash",
    value: "value"
  }
]

是的,就像使用window.location.hash一样简单。对不起,我不清楚。我需要把它们转换成一个对象,而不仅仅是一个字符串。它们呢?意思是URL中有多个哈希?只有一个哈希,但有多个值。hash=value&hash1=value1可能是这样的吗?var capturedHashParams={};window.location.hash.substring1.split和.foreachFunctionHashs{var hashvalue=hashs.split=;capturedHashParams[hashvalue[0]]=hashvalue[1];};;简明扼要。