JS,在sessionStorage中保存数组数据的问题

时间:2016-08-29 21:12:01

标签: javascript arrays split session-storage

以下是有问题的代码:

let newFriend = event.target.id;
let friends;
if (sessionStorage.getItem('friends') === null || sessionStorage.getItem('friends') === undefined || sessionStorage.getItem('friends') === '') {
    console.log('DEV_NO FRIENDS!sessionStorage[\'friends\']: ' + sessionStorage.getItem('friends'));
    friends = [newFriend];
} else {
    let currentFriends = sessionStorage.getItem('friends').split(',');
    console.log(currentFriends.length);
    // let currentFriends = JSON.parse(sessionStorage.getItem('friends'));
    console.log('DEV_sessionStorage friends: ' + currentFriends);
    console.log('DEV_inArray condition: ' + $.inArray(newFriend, currentFriends));
    if (!($.inArray(newFriend, currentFriends) !== -1)) {
        console.log('DEV_if not in array!');
        friends = currentFriends.push(newFriend);
        console.log('DEV_friends in if: ' + friends);
    }
}
let data = {friends: friends};

它挂在图片标签上。 sessionStorage会像这样填写成功登录:

if (response['friends'] !== undefined) {
    sessionStorage.setItem('friends', response['friends']);
} else {
    sessionStorage.removeItem('friends');
}

如果添加新朋友,则更新如此:

ajax(url, 'GET', 'none', 'Kinvey', function(response) {
    sessionStorage.setItem('friends', response['friends']);
});

想法是:用户可以将朋友添加到他的朋友列表中。朋友是' PUT'进入我的应用程序的后端,在名为“朋友”的列中。然后更新sessionStorage以存储新朋友。据我所知sessionStorage只支持字符串,所以我认为让我们将朋友存储为字符串,用","分隔。然后我会选择它(' currentFriends')并将该字符串拆分为数组。然后推送下一个项目并将数据发送回服务器,然后更新sessionStorage。但我根本做不到 - 我现在已经尝试了3个多小时。正如您在许多console.log()中看到的那样,出于某种原因我无法相应地处理我的数据而且我不知道我做错了什么。对不起,很长的帖子,但我真的卡在这里..

底线:正如@dfasoro所说 - 在使用REST时,应始终确保将数据保存在JSON字符串中。我的第二个问题是array.push()返回整数(数组长度)而不是新数组。

2 个答案:

答案 0 :(得分:1)

我希望这会对您有所帮助,我已经帮助您重构代码并删除了不必要的内容,我希望内联注释也能为您提供帮助。

图像挂钩代码

let newFriend = event.target.id;
let friends = [];
if (sessionStorage.getItem('friends')) {
    try {
        //this will throw an error if invalid array json is in friends sessionStorage
        friends = JSON.parse(sessionStorage.getItem('friends'));
    }
    catch (e) { }
}

//is friend in the array?
//if not add and store back into sessionStorage
if (friends.indexOf(newFriend) == -1) {
    friends.push(newFriend);
    sessionStorage.setItem('friends', JSON.stringify(friends));
}

let data = {friends: friends};
//continue with your image hook code

登录代码

//login code
if (response['friends']) {
    sessionStorage.setItem('friends', JSON.stringify(response['friends']));
} else {
    sessionStorage.removeItem('friends');
}

PUT CODE

//update PUT code
ajax(url, 'GET', 'none', 'Kinvey', function(response) {
    sessionStorage.setItem('friends', JSON.stringify(response['friends']));
});

您基本上将数据存储为JSON字符串并检索为JSON对象。您也不需要null,undefined,empty测试等。您基本上是在尝试测试一个假值。 我也非常希望您的响应对象是映射到朋友数组的标准JSON对象,而不是以逗号分隔的朋友列表,例如 {"friends": [4, 5, 3, 2]}而非“{”朋友“:”4,5,3,2“}”

答案 1 :(得分:0)

以上工作非常完美,因为sessionStorage仅使用键值对。

虽然我也使用sessionJS来获取/设置/删除来自sessionStorage的数据 也许这也会对你有帮助。