简体   繁体   English

Javascript键值数组存储

[英]Javascript key value array storing

I am here today with a question to do with key value pair arrays. 我今天在这里提出了一个与键值对数组有关的问题。

my html is as follows 我的HTML如下

<input type="checkbox" class="data" id="task_checked" value="1" email="a@a.com">
<input type="checkbox" class="data" id="task_checked" value="2" email="b@b.com">

I would like to store the following data as an array like below: 我想将以下数据存储为如下数组:

"1" => "a@a.com"
"2" => "b@b.com"

My Javascript currently is as follows: 我的Javascript目前如下:

var newTasksArr = new Array();

$("#task_checked:checked").each(function() {
    var email = $(this).attr("email");
    var id = $(this).val();
    newTasksArr['id'] = email;

});

Perhaps I am using the Jquery .each() wrong, could someone shed some light in to my question please? 也许我正在使用Jquery .each()错误,有人可以解释一下我的问题吗?

Thank you for you reading. 谢谢你的阅读。 Regards. 问候。

Two issues : 两个问题:

In Javascript, an Array may only have sequential, numeric keys. 在Javascript中,Array可能只有顺序的数字键。 If you want to use strings as keys, you want an Object. 如果要将字符串用作键,则需要一个Object。

If you want to insert an element with a key equal to the value of id , then you want newTasksArr[id] = email; 如果要插入一个键值等于id的元素,那么你需要newTasksArr[id] = email; without the quotes. 没有引号。

You're almost right, you just need to remove the quotes around 'id' so that it uses the value the id variable contains, instead of the literal string 'id' . 你几乎是对的,你只需要删除'id'周围的引号,以便它使用id变量包含的值,而不是文字字符串'id'

You should also use an object ( {} ) instead of an array ( [] ). 您还应该使用对象( {} )而不是数组( [] )。

var newTasks = {};
$("#task_checked:checked").each(function() {
    var email = $(this).attr("email");
    var id = $(this).val();
    newTasks[id] = email;
});

Avoid duplicating Ids in your markup. 避免在标记中复制ID。 The following should help, however you might want to tweek the jquery selector to include a context. 以下应该有所帮助,但是您可能希望调整jquery选择器以包含上下文。

var arr = {};

$('input:checked').each(function() {
    var $t = $(this);

    var email = $t.attr("email");
    if (!email) {
        // you may wish to do something if email is missing
    }

    var id = $t.val();
    if (!id) {
        // deal with the error
    }

    arr[id] = email;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM