主题
从localStorage中读取key为'hostarray'的数组,判读数组中是否存在主机地址1.1.1.1,如果不存在则将其插入数组开头在将其存入localStorage
indexOf
javascript
function fun(key) {
let arr = JSON.parse(localStorage.getItem(key)) || [];
if (!arr || arr.length === 0) {
localStorage.setItem(key, JSON.stringify(["1.1.1.1"]));
return;
}
if (arr.indexOf("1.1.1.1") === -1) {
arr.unshift("1.1.1.1");
localStorage.setItem(key, JSON.stringify(arr));
}
}includes
javascript
function fun(key) {
let arr = JSON.parse(localStorage.getItem(key)) || [];
if (!arr || arr.length === 0) {
localStorage.setItem(key, JSON.stringify(["1.1.1.1"]));
return;
}
if (!arr.includes("1.1.1.1")) {
arr.unshift("1.1.1.1");
localStorage.setItem(key, JSON.stringify(arr));
}
}find
javascript
function fun(key) {
let arr = JSON.parse(localStorage.getItem(key)) || [];
if (!arr || arr.length === 0) {
localStorage.setItem(key, JSON.stringify(["1.1.1.1"]));
return;
}
const isv = arr.find((elem) => elem === "1.1.1.1");
if (!isv) {
arr.unshift("1.1.1.1");
localStorage.setItem(key, JSON.stringify(arr));
}
}- some
javascript
function fun(key) {
let arr = JSON.parse(localStorage.getItem(key)) || [];
if (!arr || arr.length === 0) {
localStorage.setItem(key, JSON.stringify(["1.1.1.1"]));
return;
}
const isv = arr.some((elem) => elem === "1.1.1.1");
if (!isv) {
arr.unshift("1.1.1.1");
localStorage.setItem(key, JSON.stringify(arr));
}
}调用
javascript
fun("hostarray");