简体   繁体   中英

Searching For Existing Values in Array

I have been trying to search for an existing value in an array like below

var values = []
values.push(localStorage.getItem('items'));

console.log(values);

if (values.includes(2)) {
  alert('Already Exists.');
}

When i console the array values i have output as ["1,2,3,4,5,6"] so the code treats the array as having just one index which is index[0] which makes the search quite challenging for me.

My challenge is how to find the value 2 in the array values ?

localStorage can only hold strings. As such you need to convert the value you retrieve in to an array, which can be done using split() .

Also note that the resulting array will contain string values, so you need to use includes('2') . Try this:

 var values = "1,2,3".split(','); // just for this demo //var values = localStorage.getItem('items').split(','); console.log(values); if (values.includes("2")) { console.log('Already Exists.'); }

Hope this help you.

 var names_arr = '["1,2,3,4,5,6"]'; names_arr = names_arr.replace("'",''); function checkValue(value,arr){ var status = 'Not exist'; for(var i=0; i<arr.length; i++){ var name = arr[i]; if(name == value){ status = 'Exist'; break; } } return status; } console.log('status : ' + checkValue('3', names_arr) ); console.log('status : ' + checkValue('10', names_arr) );

First of all, this isn't jQuery, it's vanilla JS.

Second, after doing localStorage.setItem("items", [1,2,3,4,5,6]); , items in local storage will equal to "1,2,3,4,5,6" , which is no longer the appropriate format.

Rather, save your array with localStorage.setItem("items", JSON.stringify([1,2,3,4,5,6])); . When you want to retrieve those items, write let vals = JSON.parse(localStorage.getItem("items")); , and search in vals with

  • vals.includes(2) for a true/false answer,
  • vals.find(val => val === 2) for 2 or undefined,
  • val.indexOf(2) to get the index of the first element equal to 2.

Hope this helps.

firstly get the values from local storage store it in a variable, split it using the split function, then check if the number is inside the array, alert the message if it returns true

var values  =localStorage.getItem('items')
    var spliter = values.split(',')
    console.log(spliter);

    if (spliter.includes('2') == true) {
      alert('Already Exists.');
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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