Javascript 编辑本地存储代码以向每个元素添加唯一ID

Javascript 编辑本地存储代码以向每个元素添加唯一ID,javascript,local-storage,Javascript,Local Storage,我正在基于以下示例开发一项本地存储功能: CSS: 示例HTML: <div class="list" style="background:#ccc; padding:20px;"> <ul class="list-unstyled"> <li id="petty">petty</li> <li id="bedfordshire">bedfordshire</li>

我正在基于以下示例开发一项本地存储功能:

CSS:

示例HTML:

<div class="list" style="background:#ccc; padding:20px;">
    <ul class="list-unstyled">
        <li id="petty">petty</li>
        <li id="bedfordshire">bedfordshire</li>
        <li id="rearing">rearing</li>
        <li id="jane">jane</li>
        <li id="furore">furore</li>                         
    </ul>
</div>
下面是使用此代码的测试页面:

“收藏夹”数组如下所示:

favorites:"["petty","rearing","jane"]"
favorites:"[{"id":"1","name":"petty"},{"id":"2","name":"rearing"},{"id":"3","name":"jane"}]"
我需要解决如何编辑JS,以便每个元素都有一个唯一的ID,因此数组如下所示:

favorites:"["petty","rearing","jane"]"
favorites:"[{"id":"1","name":"petty"},{"id":"2","name":"rearing"},{"id":"3","name":"jane"}]"
有可能吗

我不喜欢使用jQuery,因为我必须重写代码中使用的JS,也可以在另一个页面上输出本地存储数据


谢谢

我看不出问题,只需推送
收藏夹即可。将({id:1,name:“petty”}
推送到数组中,然后将其字符串化?对于唯一的id,请获取For循环的索引,或者尝试以下操作:
Math.floor(window.performance.now()*1000)

要查找数组中是否有元素,请执行以下操作:

function isIdInArray(id) { // param id is the id youre looking for in the array
    var isInArray = false;
    favorites.forEach(function(favorite){
        if(favorite.id === id){
            isInArray = true;
        }
    });
    return isInArray;
}
要澄清是否使用
index=favorites.indexOf(id);
将在字符串中搜索字符串。
例如,
“apple.indexOf(“ple”);
将返回2,因为它发现“ple”从位置2的字符串开始。如果字符串不包含搜索字符串,例如:
“apple.indexOf(“tomato”);
返回值将为-1。您不能对数组执行indexOf。您可以使用
indexOf()
搜索字符串化数组中的索引值,但我不建议您这样做。

我看不出问题,只需按一下
收藏夹。按一下({id:1,name:“petty”}
插入数组,然后将其字符串化?对于唯一的Id,请获取For循环的索引,或者尝试以下操作:
Math.floor(window.performance.now()*1000)

要查找数组中是否有元素,请执行以下操作:

function isIdInArray(id) { // param id is the id youre looking for in the array
    var isInArray = false;
    favorites.forEach(function(favorite){
        if(favorite.id === id){
            isInArray = true;
        }
    });
    return isInArray;
}
要澄清是否使用
index=favorites.indexOf(id);
将在字符串中搜索字符串。
例如,
“apple.indexOf(“ple”);
将返回2,因为它发现“ple”从位置2的字符串开始。如果字符串不包含搜索字符串,例如:
“apple.indexOf(“tomato”);
返回值将为-1。您不能对数组执行indexOf。您可以使用
indexOf()
搜索字符串化数组中的索引值,但我不建议您这样做。

我看不出问题,只需按
收藏夹。按({id:1,name:“petty”}
插入数组,然后将其字符串化?对于唯一的Id,请获取For循环的索引,或者尝试以下操作:
Math.floor(window.performance.now()*1000)
谢谢-这很有效。我还有一个问题-你能看看我如何检查数组中是否存在该项/值,因为现有的
index=favorites.indexOf(id);
行每次单击列表项时总是返回
-1
-似乎在“名称”中插入下一项元素/键意味着indexOf再也找不到它了?我为两个请求都写了一个答案。我看不出问题,只需将
收藏夹推送({id:1,name:“petty”}
到数组中,然后将其字符串化?对于唯一的id,请使用for循环的索引,或者尝试以下操作:
Math.floor(window.performance.now()*1000)
谢谢-这很有效。我还有一个问题-你能看看我如何检查数组中是否存在该项/值,因为现有的
index=favorites.indexOf(id);
行每次单击列表项时总是返回
-1
-似乎在“名称”中插入下一项元素/键意味着indexOf再也找不到它了?我为这两个请求都写了一个答案