最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Creating Array From Window.location.hash - Stack Overflow

programmeradmin11浏览0评论

i am trying to create array from window.location.hash variable but i am failling.

My code is:

        $.each(window.location.hash.replace("#", "").split("&"), function (i, value) {
            value = value.split("=");

            var my_item = {value[0] : value[1]};
            form_data[i] = my_item; 
        });
        console.log(form_data);

Thanks.

i am trying to create array from window.location.hash variable but i am failling.

My code is:

        $.each(window.location.hash.replace("#", "").split("&"), function (i, value) {
            value = value.split("=");

            var my_item = {value[0] : value[1]};
            form_data[i] = my_item; 
        });
        console.log(form_data);

Thanks.

Share Improve this question asked Jul 13, 2010 at 4:06 mTuranmTuran 1,8345 gold badges35 silver badges59 bronze badges 6
  • 1 Are you trying to parse the hash or the search? window.location.search returns the part after the ? and before the # which is the part that has the query string key/values. – Andir Commented Jul 13, 2010 at 4:17
  • @Andir - I don't think that's the case, because the OP removed the hash sign. Then again, apparently I assumed too much already. – Kobi Commented Jul 13, 2010 at 4:24
  • I know that some implementations use the hash for things like history and whatnot, but I wanted to eliminate the possibility of a mistaken location identifier. – Andir Commented Jul 13, 2010 at 4:27
  • @Kobi +1 I removed hash sign to ready parse. – mTuran Commented Jul 13, 2010 at 4:44
  • You didn't remove everything before #. The url will get read along, which I think is not what you want. – syockit Commented Aug 25, 2010 at 6:39
 |  Show 1 more comment

7 Answers 7

Reset to default 5

Give this a try:

var hash = window.location.hash.slice(1);
var array = hash.split("&");

var values, form_data = {};

for (var i = 0; i < array.length; i += 1) {
    values = array[i].split("=");
    form_data[values[0]] = values[1];
}

console.log(form_data);

...Of course I suspect you may be wanting the search property, rather than hash, but I don't know your specific use case.

your code is correct only error is

 $.each(window.location.hash.replace("#", "").split("&"), function (i, value) {
            value = value.split("=");
            var _formItem={};
            var my_item={};
            my_item[value[0]]= value[1]; 
            form_data[i] = my_item; 
        });

JavaScript doesn't support the following notation:

var my_item = {value[0] : value[1]};

Try this instead:

var my_item = {};
my_item[value[0]] = value[1];

This will create an array, where each element has a key and a value, for example:

[{name: jason}, {age: 23}, {location: pacific}] //array of single keys

Using a hash probably makes more scene in your case, so you can call form_data['age'], and won't have to look though the array:

initialize form_data to an object:

form_data = {};

Add keys directly to it:

form_data[value[0]] = value[1];

So the result is:

{name: jason, age: 23, location: pacific} //associative array with properties

To get associative array from url hash:

function readUrlHashParams() {
    var result = {};
    var hashParam = window.location.hash.substring(1);
    var params = hashParam.split("&");

    $.each(params, function (index, set) {
        var paramSet = set.split("=");
        if (typeof (paramSet[1]) !== "undefined") {
            result[paramSet[0]] = decodeURIComponent(paramSet[1]);
        } else {
            result[paramSet[0]] = "";
        }
    });
    return result;
}

Example URL

http://localhost/Index.html#Param1=test1&Param2=Test2&Param3=

Result

var test = readUrlHashParams();
console.log(test);

Object {Param1: "test1", Param2: "Test2", Param3: ""}

Undeclared form_data is not an object, so it can't have any properties, so form_data[i] = ... will fail. Run this script in a decent browser and the console should show you a message amounting to what I just said.

edit - no it won't because the bogus object literal syntax will trip it up first as Kobi mentions. Both issues should be fixed.

Here's a sample based on the following URL:

http://www.someUrl.com/Index.htm#foo=bob&moo=alice

<!DOCTYPE html>
<html lang="en">
<head>
    <title>hash me long time</title>
</head>
<body>

    <p>Hello World!</p>

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">

        $(function () {

            var hash = window.location.hash.replace('#', '').split('&');
            var myArray = new Array();
            for (var x = 0; x < hash.length; x++) {
                var itemArray = hash[x].split('=');
                var item = new Object();
                item.key = itemArray[0];
                item.value = itemArray[1];
                myArray.push(item);
            }

            for (var x = 0; x < myArray.length; x++)
                console.log(myArray[x].key + ' is ' + myArray[x].value);

        });

    </script>
</body>
</html>

Perfect Object.

location.hash = location.hash ? location.hash : "#!";
$.each((location.hash ? location.hash.split("#!") : [""])[1].split("&"), (function () {
 y = this.split("=");
 $hash[y[0]] = y[1];
}));

If you are not yet using #! you can change it to #

发布评论

评论列表(0)

  1. 暂无评论