(javascript) 本地存储值索引
(javascript) local storage value index
我将数据设置为本地存储中名为 'todo' 的键。
结构是这样的
key: todo
value : [{"text":"text1","idx":1},
{"text":"text2","idx":2},
{"text":"text4","idx":4}]
如何找到 idx = "4" 的对象的索引?
例如,idx = 1 的对象的索引为 0。
key: todo
value : [{"text":"text1","idx":1} => index: 0
{"text":"text2","idx":2} => index: 1
{"text":"text4","idx":4}] => index: 2
假设你已经从本地存储中解析了 JSON 字符串(如果没有你可以使用 JSON.parse()
),你可以使用 .findIndex()
来获取对象的索引使用给定的 ID:
const arr = [{
"text": "text1",
"idx": 1
}, {
"text": "text2",
"idx": 2
}, {
"text": "text4",
"idx": 4
}];
const search = 4;
const res = arr.findIndex(({idx}) => idx === search); // find index of object where idx is equal to search (4)
console.log(res); // 2
使用
todo.findIndex(elem => elem.idx === 4 )
我将数据设置为本地存储中名为 'todo' 的键。
结构是这样的
key: todo
value : [{"text":"text1","idx":1},
{"text":"text2","idx":2},
{"text":"text4","idx":4}]
如何找到 idx = "4" 的对象的索引?
例如,idx = 1 的对象的索引为 0。
key: todo
value : [{"text":"text1","idx":1} => index: 0
{"text":"text2","idx":2} => index: 1
{"text":"text4","idx":4}] => index: 2
假设你已经从本地存储中解析了 JSON 字符串(如果没有你可以使用 JSON.parse()
),你可以使用 .findIndex()
来获取对象的索引使用给定的 ID:
const arr = [{
"text": "text1",
"idx": 1
}, {
"text": "text2",
"idx": 2
}, {
"text": "text4",
"idx": 4
}];
const search = 4;
const res = arr.findIndex(({idx}) => idx === search); // find index of object where idx is equal to search (4)
console.log(res); // 2
使用
todo.findIndex(elem => elem.idx === 4 )